我定义了 GCanvas,它是 Canvas 的扩展。我的意图是在类级别绑定(bind)到 GCanvas。它不起作用。
我还尝试绑定(bind)到 tk.Canvas,但它也不起作用。绑定(bind)到 root
或 GCanvas 实例工作正常。 (这两种选择对我都没有用,但我只是尝试了它们以查看发生了什么。)。运行 OS X,El Capitan。
import Tkinter as tk
class GCanvas(tk.Canvas, object):
def __init__(self, master, **kwargs):
tk.Canvas.__init__(self, master, kwargs)
@staticmethod
def enter(e):
print "enter", e.widget, e.x, e.y
@staticmethod
def leave(e):
print "leave", e.widget
@staticmethod
def motion(e):
print "motion", e.widget, e.x, e.y
approach = "bindinstance"
root = tk.Tk()
gc = GCanvas(root, width=400, height=300)
print "root is", root, "gc is", gc
gc.pack()
if approach == "bindGCanvas":
print "binding to GCanvas"
root.bind_class(GCanvas, '<Enter>', GCanvas.enter)
root.bind_class(GCanvas, '<Leave>', GCanvas.leave)
#root.bind_class(GCanvas, '<Motion>', GCanvas.motion)
elif approach == "bindCanvas":
print "binding to Canvas"
root.bind_class(tk.Canvas, '<Enter>', GCanvas.enter)
root.bind_class(tk.Canvas, '<Leave>', GCanvas.leave)
#root.bind_class(tk.Canvas, '<Motion>', GCanvas.motion)
elif approach == "bindinstance":
print "binding to instance"
gc.bind('<Enter>', GCanvas.enter)
gc.bind('<Leave>', GCanvas.leave)
#gc.bind('<Motion>', GCanvas.motion)
else:
print "binding to root"
root.bind('<Enter>', GCanvas.enter)
root.bind('<Leave>', GCanvas.leave)
#root.bind('<Motion>', GCanvas.motion)
root.mainloop()
最佳答案
bind_class
中的“类”是指tk库使用的内部类名,不是python类名。更准确地说,在这种情况下,它指的是一个 bind 标签,它恰好与 tk 类同名,它也恰好与核心 Tkinter 类之一同名(例如: Toplevel
、Canvas
等)。
要在类级别绑定(bind)到 GCanvas
,最简单的方法是将名为 GCanvas
的绑定(bind)标签添加到您的 Canvas ,如下例所示:
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))
然后您可以像这样使用 bind_class
:
root.bind_class("GCanvas", "<Enter>", GCanvas.enter)
root.bind_class("GCanvas", "<Leave>", GCanvas.leave)
有关绑定(bind)标签的更多信息,请参阅这些对其他一些 tkinter 问题的回答:
关于python-2.7 - 对 Tkinter bind_class 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40421993/