Confused about Tkinter bind_class

落花浮王杯 提交于 2019-12-02 00:53:39
Bryan Oakley

The "class" in bind_class refers to the internal class name used by the tk library, not the python class name. More precisely, in this context it refers to a bind tag, which happens to be the same name as the tk class, which also happens to be the same name as one of the core Tkinter classes (eg: Toplevel, Canvas, etc).

To bind to GCanvas at the class level, the simplest thing would be to add a bind tag named GCanvas to your canvas, as in the following example:

class GCanvas(tk.Canvas, object):
    def __init__(self, master, **kwargs):
        ...
        # get the current bind tags
        bindtags = list(self.bindtags())

        # add our custom bind tag before the Canvas bind tag
        index = bindtags.index("Canvas")
        bindtags.insert(index, "GCanvas")

        # save the bind tags back to the widget
        self.bindtags(tuple(bindtags))

You can then use bind_class like so:

root.bind_class("GCanvas", "<Enter>", GCanvas.enter)
root.bind_class("GCanvas", "<Leave>", GCanvas.leave)

For more information about bind tags, see these answers to some other tkinter questions:

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