2
我定義GCanvas,畫布的延伸。我的意圖是在課堂上對GCanvas進行綁定。它不工作。困惑的Tkinter bind_class
我也試圖綁定到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()
謝謝!所以我根本不需要定義一個Python類;我只需要在我的畫布上添加一個獨特的綁定標籤,對吧? – Eduardo
@Eduardo:對。我建議使用一個類來創建一個新類型的畫布,但嚴格來說你不需要。 –