我正在 Win7 机器上使用 Python 2.7 和 Tkinter GUI。
在某些情况下,我想完全覆盖 Tab 键的正常默认行为,但前提是存在某些条件。之后我想恢复到默认行为。 (请注意,目前我对 Tab 键感兴趣,但在某些时候我可能也需要对其他键执行此操作。)
下面的代码片段(不是我的实际应用程序,只是一个精简的示例)为我提供了我想要的完全覆盖,但是一旦我执行了以下操作,它就会产生“永久”消除默认行为的副作用unbind
,使 Tab 键无效:
import Tkinter as tk
#Root window
root = tk.Tk()
tabBlock = ''
#Tab override handler
def overrideTab(*args):
global tabBlock
if (ctrlChk4.get()==1):
tabBlock = root.bind_all('<Tab>',stopTab)
else:
root.unbind('<Tab>',tabBlock)
def stopTab(*args):
print 'Tab is overridden'
#Control variable
ctrlChk4 = tk.IntVar()
ctrlChk4.trace('w',overrideTab)
#GUI widgets
fra1 = tk.Frame(root)
chk1 = tk.Checkbutton(fra1,
text='First checkbutton')
chk2 = tk.Checkbutton(fra1,
text='Second checkbutton')
chk3 = tk.Checkbutton(fra1,
text='Third checkbutton')
chk4 = tk.Checkbutton(fra1,
text='Tab override',
variable=ctrlChk4)
fra1.grid(row=0,column=0,sticky=tk.W,padx=10,pady=10)
chk1.grid(row=0,column=0,sticky=tk.W,padx=(10,0),pady=(5,0))
chk2.grid(row=1,column=0,sticky=tk.W,padx=(10,0),pady=(5,0))
chk3.grid(row=2,column=0,sticky=tk.W,padx=(10,0),pady=(5,0))
chk4.grid(row=3,column=0,sticky=tk.W,padx=(10,0),pady=(5,0))
tk.mainloop()
我尝试过做不同的事情bind
代替bind_all
,并且还设置add
绑定方法的参数1
or '+'
。这些变化都给了我相同的结果:一旦我执行了这些操作,它们就可以让我恢复默认行为unbind
但它们也允许默认行为继续bind
已生效。
我已经搜索了各种在线资源,寻找一种“保存和恢复”原始绑定的方法,或者“非破坏性地”完全覆盖默认行为,但两者都没有运气。
有什么办法可以完成我想做的事情吗?
编辑:当谈到 Tab 键时,我知道我可以模仿/替换原始的默认行为
root.focus_get().tk_focusNext().focus_set()
...但这也是一个普遍问题。如果我需要在某个模块的上下文中覆盖某个键(任何键)(例如,包含我自己的自定义类,用于我自己的自定义调整 Tkinter 小部件),但随后恢复到该键在调用模块中,我该怎么做?是否可以?