Python Tkinter - 恢复原始默认密钥绑定

时间:2014-01-30 21:48:12

标签: python-2.7 tkinter event-binding

我在Win7机器上使用Python 2.7和Tkinter GUI。

在某些情况下,我希望完全覆盖Tab键的正常默认行为,但只要存在某些条件。之后,我想恢复默认行为。 (请注意,目前我对Tab键感兴趣,但我可能在某些时候也需要为其他键执行此操作。)

下面的代码片段(不是我的实际应用,只是一个精简的示例)为我提供了我想要的完全覆盖,但它具有“永久”消除默认行为的副作用{I { 1}},使Tab键无效:

unbind

我尝试过执行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} }。这些变化都给了我相同的结果:他们让我在执行1后恢复默认行为,但它们也允许在'+'生效时继续默认行为。

我已经搜索了各种在线资源,以便“保存并恢复”原始绑定,或者“非破坏性地”完全覆盖默认行为,但无论如何都没有运气。

有没有办法完成我想要做的事情?

编辑:说到Tab键,我知道我可以用

模仿/替换原来的默认行为
unbind

......但这也是一个普遍的问题。如果我需要覆盖一个键 - 任何键 - 在某个模块的上下文中(比如,一个包含我自己的自定义类的自定义调整的Tkinter小部件),但是然后恢复到绑定/行为那个键在调用模块中,我怎么能这样做?有可能吗?

1 个答案:

答案 0 :(得分:3)

好的,我试了一下并为你找到答案。我在评论中的建议是有效的。总之,return "break"何时要覆盖它。当你不这样做时不要。使用bind代替bind_all。而且,如果你还没有在你的args中这样做,请考虑事件参数,否则它将无法正常工作。您实际上仍然将某些内容绑定到密钥,但它仅覆盖某些指定环境中的默认功能。这是代码(适用于Python 2.x和3.x):

import sys
if sys.version_info[0]<3:
    import Tkinter as tk
else:
    import tkinter as tk

#Root window
root = tk.Tk()

#Tab override handler
def overrideTab(*args):
    root.bind('<Tab>', stopTab)

def stopTab(event=None, *args):
    if ctrlChk4.get()==1:
        print('Tab is overridden')
        return "break"
    else:
        print('Tab is not overridden') #Note that it still prints this.

#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()
相关问题