2016-11-04 82 views
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() 

回答

3

「階級」在bind_class是指由TK庫,而不是蟒蛇類名稱中使用的內部類的名字。更確切地說,在這種情況下它是指一個bind標籤,這恰好是相同的名稱tk類,這也恰好是相同的名稱(核心的Tkinter類之一例如:ToplevelCanvas等)。

綁定到GCanvas在類級別,最簡單的做法是添加一個名爲GCanvas到你的畫布綁定標籤,如下面的例子:

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) 

有關綁定標記的詳細信息,請參閱以下解答一些其他Tkinter的問題:

+0

謝謝!所以我根本不需要定義一個Python類;我只需要在我的畫布上添加一個獨特的綁定標籤,對吧? – Eduardo

+0

@Eduardo:對。我建議使用一個類來創建一個新類型的畫布,但嚴格來說你不需要。 –