[英]How to freeze use of key tab in tkinter python
我正在尝试制作一个简单的应用程序,该应用程序在键入时会打乱键盘字母。 我正在与tkinter一起使用python。 我有一个文本小部件,我需要在应用程序中禁用键选项卡。 我尝试使用以下代码。
text.bind("<Tab>", no_op)
这里no_op是下面给出的函数:
def no_op(self):
return "break"
但是我没有得到预期的结果。 我将在下面发布整个代码。
import Tkinter as tk
def onKeyPress(event):
first=event.char
second=ord(first)
if second==32:
second=chr(second)
text.insert('end', '%s' % (second ))
elif second==8:
length = len(text.get(1.0, 'end'))
contents = text.get(1.0, 'end')
newcon = contents[:-2]
#text.insert('end', '%s' % (length ))
text.delete(1.0,'end')
text.insert('end', '%s' % (newcon ))
elif(second>=65 and second<=90 or second>=97 and second<=122):
second=chr(second+3)
text.insert('end', '%s' % (second ))
def no_op(self):
return "break"
root = tk.Tk()
root.config(cursor='none')
#root.attributes('-zoomed',True)
text = tk.Text(root, background='white', foreground='black', font=('Comic Sans MS', 12))
text.pack(expand=True,)
text.bind("<Tab>", no_op)
text.bind("<Button-1>", no_op)
text.config(cursor="none")
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
( 注意 :问题是当其他小部件具有焦点时按下Tab键时,文本光标进入文本区域。然后,如果我按任何字母,则“ a”和“ d”都插入到文本字段。我要解决此问题。)
您的问题不在于Tab键,问题在于焦点管理。 仅当文本窗口小部件从未获得键盘焦点时,您才能使代码工作。 至少有两种解决方案:
首先,您无需尝试更改选项卡(以及Shift-Tab)的行为,而只需在文本小部件获得焦点时就移动焦点。 例如:
text.bind("<FocusIn>", lambda event: root.focus_set())
这将阻止文本小部件获得焦点,并且您的代码应该可以工作。
另一个解决方案是将<KeyPress>
绑定修改为在文本小部件上而不是在根小部件上,然后仅拒绝对按键的所有处理。 这意味着要做text.bind('<KeyPress>', ...)
而不是root.bind...
然后,您需要修改onKeyPress
以返回"break"
以防止发生默认的文本小部件绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.