简体   繁体   中英

Python tkinter textvariable in label widget

I have made a variable called 'localtime2' within my def in the code and then have a label which says 'textvariable=localtime2.' the problem is that it does not display the information about the variable.

localtime2 = time.asctime(time.localtime(time.time()))
tk.Label(roots, font=('arial', 16, 'bold'), textvariable=localtime2, bd=16, anchor="w").grid(row=2, column=0)

This is all I have in the code about this variable and it is not coming up with any error in the terminal. It just doesnt show at all.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM