Tkinter code runs without mainloop, update, or after

前端 未结 1 1658
我寻月下人不归
我寻月下人不归 2020-12-22 14:21

I have been trying to use tkinter to make a gui to select some excel files and sheets from those files.

I have a lot of experience in python, but I\'d probably say a

相关标签:
1条回答
  • 2020-12-22 15:06

    mainloop enters an event listening loop for your tk.Tk() application.

    You should create only one object with Tk() in every tkinter application.

    Now this loop will "globally" listen for GUI events and will call your registered callbacks (event handlers). Code before the mainloop call will run but nothing will be shown or updated in the screen until you call it. No event (user input, mouse movement, keyboard and others) will be queued and responded to before that. But the widgets are created and configured, just not shown yet. If you call root.update() without ever entering the mainloop you will eventually see the window flash and disappear because everything is running, and you force window refresh, but then suddenly the program ends.

    So configure your GUI and in the end always run root.mainloop()

    Now when you call wait_window, you are creating a local event loop (and blocking the mainloop if it was running). For a perfect explanation of wait_window by Brian see here

    What happened to you is that your app is happily running with your local event loop, but without mainloop. That would be a strange thing to do. Even if you are making as Brian explains, a modal window, you want to "return" to the mainloop after the window closes.

    As for the after method it just registers a callback function to run after your choosen time, or after the mainloop becames idle, with after_idle (nothing more to refresh, no events in the queue..., also think as soon as possible). And if you want to re-run that function again in the same way it should re-register with after or after_idle before returning.

    So always use your mainloop() ending call - or should I say event loop starting call :)

    Edit:

    Also, don't do things in your code that are slow, or that may block the loops, such as calling sleep or any other blocking function. That will freeze the GUI, until the block ends.

    0 讨论(0)
提交回复
热议问题