Update Tkinter Label from variable
The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True
block preceding the line root.mainloop()
.
GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.
from tkinter import *
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
t = Entry(root, textvariable = var)
t.pack()
root.mainloop() # the window is now displayed
I like the following reference: tkinter 8.5 reference: a GUI for Python
Here is a working example of what you were trying to do:
from tkinter import *
from time import sleep
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
for i in range(6):
sleep(1) # Need this to slow the changes down
var.set('goodbye' if i%2 else 'hello')
root.update_idletasks()
root.update
Enter event loop until all pending events have been processed by Tcl
.
How to Update text in Tkinter Label/Canvas widget using for loop?
import tkinter as tk
root = tk.Tk()
root.attributes("-fullscreen", True)
root.bind("<F11>", lambda event: root.attributes("-fullscreen", not root.attributes("-fullscreen")))
root.bind("<Escape>", lambda event: root.attributes("-fullscreen", False))
root.bind("<F1>", lambda event: os.exit(0))
w = tk.StringVar()
labelFlash = tk.Label(root, bg='Black', width=root.winfo_screenwidth(), height=root.winfo_screenheight(),
anchor="center", text="Sample", fg="White", font="Times " , textvariable=w)
labelFlash.pack()
MSG="Hello World"
str_list=[]
for i in range(len(MSG)):
str_list.append(MSG[:i+1])
words=str_list
indx=0
def update():
global indx
if indx>=len(words):
indx=0
w.set(words[indx])
labelFlash.config(text=words[indx])
indx+=1
root.after(500, update)#500 ms
update()
root.mainloop()
Update Label Text in Python TkInter
You cannot do precisely what you ask -- you can't associate both a static string and a variable to a label at the same time. There are things you can do to get the desired effect, but all you're doing is adding complexity with no real gain. For example, you can assign an instance of StringVar
to the textvariable
attribute of the Label
widget. When you do that, any update to the variable will update the label. However, you end up having to make a function call to update the variable, so you don't really gain anything over making a function call to update the label directly.
Another option is to use two labels -- one for the static text and one for the variable. Put them side-by side with no border so the user won't notice. Then, when you update the variable you'll get the desired effect. However, you're still having to make a function call to set the variable so you don't really gain much.
Yet another option is to use two instances of StringVar
-- one for the label, and another for the name. You can put a trace on the name variable so that when it changes, you automatically update the other variable with the static string and the value of the name variable, and that will cause the label to be automatically updated. Again, however, you're having to make a function call to put everything in motion
So, as you can see, there are options, but they all add complexity to your code with no real gain over simply updating the label directly. The only time these other methods gain you an advantage is when the value needs to appear in more than one widget at once. In that case you can associate the variable with two or more widgets, and a single function call will update all associated widgets.
Update label elements in Tkinter
Basically you don't need to create the Label each iteration, there are several ways of how to update Label in tkinter.
For example:
1.
window = tkinter.Tk()
text = tkinter.StringVar()
text.set('old')
lb = tkinter.Label(window, textvariable=text)
...
text.set('new')
2.
lb = tkinter.Label(window, text="What is " + str(number1) + "x" + str(number2) + " ?")
lb['text'] = 'new'
3.
lb = tkinter.Label(window, text="What is " + str(number1) + "x" + str(number2) + " ?")
lb.config(text='new')
How to update Tkinter Label Text before executing some other function?
Seems to work for me after changing a couple of things (others were mostly just little optimizations).
- Changed
func()
to not usetime.sleep()
as shown below—theafter()
universal widget method can (also) be used to do this and using it doesn't interfere with themainloop()
running the way callingsleep()
would. - Called the universal widget method
update()
instead ofupdate_idletasks()
after destruction of the widgets—but still before the counting loop runs.
Here's some documentation describing how to use the universal widget method after()
this way (as well as what the update()
method does).
FWIW: You'll be able see what's happening better if you add something like a root.geometry('600x400')
line following the root = tk.Tk()
statement in the initialization section of the example code in your question (not shown here) which will prevent the window from resizing after the widgets are destroyed and the display is updated.
def func():
widgets = root.grid_slaves()
for widget in widgets:
if widget.grid_info()['row']: # Don't need all that int() != 0 stuff.
widget.destroy()
startPrompt.configure(text="Updated Text") # Only need to call once.
root.update() # Update display (startPrompt.update() also works here)
# Just an example of something running, to verify that the loop executes
# AFTER the tkinter window has been updated.
for i in range(10):
print(i)
# time.sleep(0.5) # Don't use sleep in tkiner programs.
root.after(500) # Pause 500 millisecs.
Adding and updating new widget in tkinter in runtime
You are getting the error because every thing you retrieve from Text
widget is a string and you cannot directly pass an string to .config
method, you need a keyword and then you can assign value which can be string.
According to your question and the comments on the question, what i have figured out is:
- You want to run
lable.config(bg='red')
from theText
widget. - You want to change the property of specific widget.
Here's what you can do:
- To run Tkinter code form
Text
widget, you can use:
getattr
methodeval
method
- Just to change property of widget:
def update_Frame():
global bcd
a = u_text_wid.get("1.0", "end-1c")
b=a.split(",")
c=[tuple(i.split("=")) if "=" in i else i for i in b]
d=dict(i for i in c)
for key,value in d.items():
bcd[key]=value
- We can use string to change property only in this format
widget_name[key]=value
.
Some Useful Links:
- Eval()
- Getattr()
Related Topics
Parsing Boolean Values with Argparse
How to Get Different Colored Lines for Different Plots in a Single Figure
How to Access "Static" Class Variables Within Methods in Python
Typeerror: Not All Arguments Converted During String Formatting Python
Python: Ignore 'Incorrect Padding' Error When Base64 Decoding
Scraping: Ssl: Certificate_Verify_Failed Error for Http://En.Wikipedia.Org
Case Insensitive Regular Expression Without Re.Compile
Django Set Default Form Values
How to Activate an Anaconda Environment
Quick and Easy File Dialog in Python
Create a .CSV File with Values from a Python List
Pandas: Rolling Mean by Time Interval
Pandas Timeseries Plot Setting X-Axis Major and Minor Ticks and Labels
Can Pandas Automatically Read Dates from a CSV File
Python Ctypes - Loading Dll Throws Oserror: [Winerror 193] %1 Is Not a Valid Win32 Application