Destroy events executes the binded function 5 times

左心房为你撑大大i 提交于 2021-01-29 09:22:53

问题


I have some code in python using the tkinter module. I've been trying to bind a function to the "<Destroy>", but each time I run the code and I close the window, the binded function executs 5 times. Here is the code:

def bind_events(self):
        ''' binding the events to their functions '''

        self.master.bind("<Destroy>", lambda x: print("OK"))

This code is a class function. Then the output I obtain this:

>>> OK
OK
OK
OK
OK

Is there any solution for this problem. Thank you for your time, and sorry for my English.


回答1:


If you bind an event to the root window, that binding is attached to every widget. Thus, if you have a root window with four other widgets, when you destroy the window your bound function will be called five times - once for every widget.

An easy way to see this happen is to modify your function to not just print "OK", but to also print the widget associated with the event:

self.master.bind("<Destroy>", lambda event: print("{}: OK".format(event.widget)))

This has to do with the fact that you aren't actually binding to a widget per se, you are binding to a binding tag that has the same name as the widget. Every widget has a set of binding tags associated with it in addition to itself:

  • It will have a binding tag for itself
  • It will have a binding tag for the widget class (which is how widgets get their default behavior)
  • It will have a binding tag for the toplevel window (or root) for that widget,
  • It will have the special binding tag "all"

Thus, when you bind to the root window, ever widget will inherit that binding. If you want to bind to the root window and only the root window, the most common solution is to bind to a function, and in that function only take an action of the widget is the root window.

For example:

def on_destroy(self, event):
    if event.widget == self.master:
        print("{}: OK".format(event.widget))

self.master.bind("<Destroy>", self.on_destroy)


来源:https://stackoverflow.com/questions/58328686/destroy-events-executes-the-binded-function-5-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!