Python tkinter textvariable in label widget
Python tkinter textvariable in label widget
Edit: The solution to the original post was using text=localtime2.get()
instead of textvariable=localtime2
in the label widget (for some strange reason). However, my original answer is still correct as tkinter variables should be used and so I will keep it up.
You must use tkinter variables in tkinter widgets and not normal python variables. Tkinter variables are slightly different to normal variables and must first be defined as a specific data type. For example, a variable which contains a string must be first created like so:
string_variable = tk.StringVar()
likewise a boolean would be created like so:
boolean_variable = tk.BooleanVar()
Read here for more information on tkinter variables.
These variables are in fact classes so in order to set them use must call the .set()
method. Therefore to set a tkinter String variable to a string you would use the following code:
string_variable = tk.StringVar() # Create the variable
string_variable.set(a string) # Set the value of the variable
Thus to fix your code you need to make localtime2
a tkinter variable and set it to the time using the .set()
method.
Example:
localtime2 = tk.StringVar() # Create the localtime2 string variable
localtime2.set(time.asctime(time.localtime(time.time()))) # Set the variable
tk.Label(roots, font=(arial, 16, bold), textvariable=localtime2, bd=16, anchor=w).grid(row=2, column=0)
Whenever there is a change in a tkinter variable, the update is automatically reflected everywhere. Because of this property you cannot use a normal python variable here.
Try using StringVar()
and then setting the variable content using set()