Why does the update method in Tkinter cause the window to freeze?

1.6k views Asked by At

First of all, I know Tkinter isn't thread safe and this problem has something to do with that but I wanted to find out formally why this code makes a window that displays but is unresponsive.

from Tkinter import *
root = Tk()
c = Canvas()
c.pack()
c.create_line(10,10, 30, 30)
root.update()

I want to know why it crashes. I know the last line should contain a mainloop() but if as this post says mainloop just continuously calls the two methods there is no reason the above code should be unresponsive.

2

There are 2 answers

2
fferri On BEST ANSWER

update() just processes events once.

mainloop() (as the name implies) is a loop that continuously processes events.

In your code you call root.update() only once, that's why your program becomes unresponsive or terminates.

Put the call to root.update() in a while loop, and it will work as expected:

while True:
    root.update()

However, if this solves your problem, probably you just want to call root.mainloop().

1
Bryan Oakley On

The reason it exits (not crashes) is because it has done everything you've asked it to do. You told it to process any pending events, and then like every other python program, when it runs out of statements, it exits.

A GUI needs to be able to continuously process events. In tkinter you do that by calling the mainloop method of the root window. This will not return (and thus, your program won't exit) until the root window has been destroyed.

from Tkinter import *
root = Tk()
...
root.mainloop()

If your real code is running in a thread, the problem is likely due to threading. The exact code in your question, when run in a single threaded interpreter, will exit almost immediately after the root window is displayed.