Which events can be bound to a Tkinter Frame?
-
05-07-2019 - |
Question
I am making a small application with Tkinter. I would like to clean few things in a function called when my window is closed. I am trying to bind the close event of my window with that function. I don't know if it is possible and what is the corresponding sequence.
The Python documentation says: See the bind man page and page 201 of John Ousterhout’s book for details
.
Unfortunately, I don't have these resources in my hands. Does anybody know the list of events that can be bound?
An alternative solution would be to clean everything in the __del__
of my Frame class. For an unknown reason it seems that it is never called. Does anybody knows what can be the cause? Some circular dependencies?
As soon as, I add a control (uncomment in the code below), the __del__
is not called anymore. Any solution for that problem?
from tkinter import *
class MyDialog(Frame):
def __init__(self):
print("hello")
self.root = Tk()
self.root.title("Test")
Frame.__init__(self, self.root)
self.list = Listbox(self, selectmode=BROWSE)
self.list.pack(fill=BOTH, expand=1)
self.pack(fill=BOTH, expand=1)
def __del__(self):
print("bye-bye")
dialog = MyDialog()
dialog.root.mainloop()
Solution
I believe this is the bind man page you may have been looking for; I believe the event you're trying to bind is Destroy
. __del__
is not to be relied on (just too hard to know when a circular reference loop, e.g. parent to child widget and back, will stop it from triggering!), using event binding is definitely preferable.
OTHER TIPS
A more-or-less definitive resource for events is the bind man page for Tk. I'm not exactly clear what you're wanting to do, but binding on "<Destroy>"
is probably the event you are looking for. Whether it does what you really need, I don't know.
...
self.bind("<Destroy>", self.callback)
...
def callback(self, event):
print("callback called")