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.