在Tcl/Tk中執行此操作的標準方法很簡單:您使用相同的綁定命令,但沒有最終參數。
bind .b <Button-1> doSomething
puts "the function is [bind .b <Button-1>]"
=> the function is doSomething
你可以做的Tkinter類似的事情,但結果是,不幸的是,沒有那麼有用:
e1.bind("<Button-1>",doSomething)
e1.bind("<Button-1>")
=> 'if {"[-1208974516doSomething %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %X %Y %D]" == "break"} break\n'
顯然,Tkinter的是做了很多的封面下方雜耍的。一個解決辦法是編寫記住這個給你一個小幫手過程:
def bindWidget(widget,event,func=None):
'''Set or retrieve the binding for an event on a widget'''
if not widget.__dict__.has_key("bindings"): widget.bindings=dict()
if func:
widget.bind(event,func)
widget.bindings[event] = func
else:
return(widget.bindings.setdefault(event,None))
你會使用這樣的:
e1=Entry()
print "before, binding for <Button-1>: %s" % bindWidget(e1,"<Button-1>")
bindWidget(e1,"<Button-1>",doSomething)
print " after, binding for <Button-1>: %s" % bindWidget(e1,"<Button-1>")
當我運行上面的代碼我得到:
before, binding for <Button-1>: None
after, binding for <Button-1>: <function doSomething at 0xb7f2e79c>
作爲一個最後的警告,我不使用Tkinter太多,所以我不確定分支是什麼動態添加一個屬性到一個小部件實例。它似乎是無害的,但如果不是,你總是可以創建一個全局字典來跟蹤綁定。
Cristian使用了pprint,這對lambda來說可以。 – nosklo 2008-09-26 06:40:41