質問

I've asked this before - but I think I phrased it incorrectly.

  1. What I essentially want is to have a user fill out a tkinter entry box, and have the value saved - somewhere.
  2. I the want to click on a button, and have the user's entered text to manipulate.

I want essentially what is below - although that doesn't work at all - as I can't enter a StringVar there, apparently. I'm really at my wits end here :(

How can I rewrite this, so it will work?

class Driver():
    firstname = StringVar()

    def __init__(self):
        root = Tk()
        root.wm_title("Driver")

        firstname_label = ttk.Label(root, text="First Name *").grid(row=0, column=0)
        firstname_field = ttk.Entry(root, textvariable=self.firstname).grid(row=0, column=1)

        ttk.Button(root, text="Send", command=self.submit).grid()
        root.mainloop()

    def submit(self):
        print(self.firstname.get())

I've having lots, and lots of trouble with this. It seems to printing blank values and references to the variable - rather than the value inside it

役に立ちましたか?

解決

You cannot use StringVar in this way -- you can't create a StringVar until after you've created the root window. Because you are creating the root window inside the constructor the code will throw an error.

The solution is to move the creation of the StringVar inside your constructor:

class Driver():

def __init__(self):
    root = Tk()
    root.wm_title("Driver")

    self.firstname = StringVar()
    firstname_label = ttk.Label(root, text="First Name *").grid(row=0, column=0)

Note that the way you've written the code, firstname_label and firstname_field will always be None, because that is what grid returns. It's always best to separate widget creation from layout.

Also, you don't really need the StringVar under most circumstances (assuming you correctly store a reference to the widget). Just omit it, and when you want the value of the entry widget you can just get it straight from the entry widget:

...
self.firstname_field = Entry(...)
...
print(self.firstname_field.get())

The use of a StringVar is only necessary if you want to share the value between widgets, or you want to put a trace on the variable.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top