我在 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()
我尝试了做 abind
而不是 a 的变体,并将绑定方法bind_all
的参数设置为or 。这些变化都给了我相同的结果:一旦我这样做,它们让我恢复默认行为,但它们也允许默认行为在有效时继续。add
1
'+'
unbind
bind
我已经搜索了各种在线资源,以寻找一种“保存和恢复”原始绑定的方法,或者“非破坏性地”完全覆盖默认行为,但在这两种情况下都没有运气。
有什么办法可以完成我想做的事情吗?
编辑:当谈到 Tab 键时,我知道我可以模仿/替换原来的默认行为
root.focus_get().tk_focusNext().focus_set()
...但这也是一个通用问题。如果我需要在某个模块的上下文中覆盖一个键——任何键——(例如,一个包含我自己的自定义类的我自己的自定义调整的 Tkinter 小部件),然后恢复到绑定/行为那个键,因为它在调用模块中,我该怎么做?是否可以?