Okay, so I\'m just trying to get some clarification on why my code is not working like I thought it would.
I am building a GUI, and I want to display text on a
The UI will update every time the event loop is entered. This is because painting is done via events (also known as "idle tasks" because they are done when the UI is otherwise idle).
Your problem is this: when you write a loop and do time.sleep
, the event loop will not be entered while that loop is running, so no redrawing will occur.
You can solve your problem in at least a couple different ways. For one, you can just call update_idletasks
which will refresh the screen. That will solve the repainting, but because you are sleeping the UI will be unresponsive during your loop (since button and key presses aren't "idle tasks").
Another solution is to write a function that takes a string, pulls one character off the string and adds it to the widget. Then it arranges for itself to be called again via the event loop. For example:
import Tkinter as tk
class App(tk.Tk):
def __init__(self,*args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.label = tk.Label(self, text="", width=20, anchor="w")
self.label.pack(side="top",fill="both",expand=True)
self.print_label_slowly("Hello, world!")
def print_label_slowly(self, message):
'''Print a label one character at a time using the event loop'''
t = self.label.cget("text")
t += message[0]
self.label.config(text=t)
if len(message) > 1:
self.after(500, self.print_label_slowly, message[1:])
app = App()
app.mainloop()
This type of solution guarantees that your UI stays responsive while still running your code in a loop. Only, instead of using an explicit loop you add work to the already running event loop.