Tkinter understanding mainloop

后端 未结 3 1191
离开以前
离开以前 2020-11-21 06:17

Till now, I used to end my Tkiter programs with: tk.mainloop(), or nothing would show up! See example:

from Tkinter import *
import random
impor         


        
3条回答
  •  不知归路
    2020-11-21 07:10

    while 1:
        root.update()
    

    ... is (very!) roughly similar to:

    root.mainloop()
    

    The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

    while the_window_has_not_been_destroyed():
        wait_until_the_event_queue_is_not_empty()
        event = event_queue.pop()
        event.handle()
    

    ... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

    Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

提交回复
热议问题