How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Matt has shown one classic modification of the close button.
The other is to have the close button minimize the window.
You can reproduced this behavior by having the iconify method
be the protocol method's second argument.
Here's a working example, tested on Windows 7:
In this example we give the user two new exit options:
the classic file menu -> Exit, and also the Esc button.
Use the closeEvent
Depending on the Tkinter activity, end esp. when using Tkinter.after, stopping this activity with
destroy()
-- even by using protocol(), a button, etc. -- will disturb this activity ("while executing" error) rather than just terminate it. The best solution in almost every case is to use a flag. Here is a simple, silly example of how to use it (although I am certain that most of you don't need it! :)This terminates graphics activity nicely. You only need to check
running
at the right place(s).Tkinter supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called
WM_DELETE_WINDOW
, and is used to define what happens when the user explicitly closes a window using the window manager.You can use the
protocol
method to install a handler for this protocol (the widget must be aTk
orToplevel
widget):Here you have a concrete example: