我定义了 GCanvas,Canvas 的扩展。我的目的是在类级别绑定到 GCanvas。它不起作用。
我还尝试绑定到 tk.Canvas,但它也不起作用。绑定到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()