pythontkintertkinter-entry

Tkinter entry text not updated when using .set() (but textvariable is)


I am having trouble setting a default value for a text entry widget in a Python 3.9 tkinter application. I am using a StringVar as the text variable, and changing it using .set().

I am trying to pre-set the date (and time).

If I do it in a class, the box is empty, even though the value has been changed:

class test:
    def __init__(self, root):
        # Content frame widget
        mainframe = ttk.Frame(root, padding="3 3 12 12")
        mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
        
        ttk.Label(root, text="Date/Time").grid(
            column=1, row=3, sticky=E, padx=(5, 0)
        )
        self.date_value = StringVar()
        self.date_value.set(datetime.today().strftime("%Y-%m-%d"))
        ttk.Entry(root, width=10, textvariable=self.date_value).grid(column=2, row=3, sticky=E)
        print(self.date_value.get())

root = Tk()
test(root)
root.mainloop()

enter image description here

If I do it outside the class it works.

root = Tk()

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))

ttk.Label(root, text="Date/Time").grid(
    column=1, row=3, sticky=E, padx=(5, 0)
)
date_value = StringVar()
date_value.set(datetime.today().strftime("%Y-%m-%d"))
ttk.Entry(root, width=10, textvariable=date_value).grid(column=2, row=3, sticky=E)
print(date_value.get())

root.mainloop()

enter image description here

What's weird is I do sometimes see it work in the first example, when there's some other error in my code that causes a subsequent error it correctly shows with the date filled.

I'm sure I'm missing something very obvious but would love to know what it is!


Solution

  • It is because the instance of test() is not store in a variable, so it is garbage collected after it is created.

    Just assign the instance to a variable:

    ...
    root = Tk()
    app = test(root)
    root.mainloop()