当我尝试在Tkinter文本小部件上使用KeyRelease事件时,它有时在event.char中提供小写字符,但在文本小部件中显示大写字符。当我轻快地按下shift键,然后按下一个字母时,就会出现这种情况。如何使用Tkinter文本小部件上的KeyRelease事件可靠地捕获大小写正确的字符?
下面是我在我的MacBook专业版上测试的示例代码:
from Tkinter import *
class App:
def __init__(self):
# create application window
self.root = Tk()
# add frame to contain widgets
frame = Frame(self.root, width=768, height=576,
padx=20, pady=20, bg="lightgrey")
frame.pack()
# add text widget to contain text typed by the user
self.text = Text(frame, name="typedText", bd="5", wrap=WORD, relief=FLAT)
self.text.bind("<KeyRelease>", self.printKey)
self.text.pack(fill=X)
"""
printKey sometimes prints lowercase letters to the console,
but upper case letters in the text widget,
especially when I lightly and quickly press Shift and then some letter
on my MacBook Pro keyboard
"""
def printKey(self, event):
print event.char
def start(self):
self.root.mainloop()
def main():
a = App()
a.start()
if __name__ == "__main__":
sys.exit(main())发布于 2012-01-29 12:19:54
发生的情况是,您在字母键之前释放了shift键。shift键是在插入字符时按下的,这就是为什么小工具会得到一个大写字符,但是当您的快捷键释放绑定被处理时,shift键已经被释放,所以您看到的是小写字符。
如果要打印正在插入的内容,请绑定到按键而不是释放键。
发布于 2012-01-30 01:07:38
基于Bryan的洞察力,我修改了代码,它似乎可以工作:
from Tkinter import *
import string
class App:
def __init__(self):
# create application window
self.root = Tk()
# add frame to contain widgets
frame = Frame(self.root, width=768, height=576, padx=20, pady=20, bg="lightgrey")
frame.pack()
# add text widget to contain text typed by the user
self.text = Text(frame, name="typedText", bd="5", wrap=WORD, relief=FLAT)
self.text.bind("<KeyPress>", self.printKey)
self.text.pack(fill=X)
"""
this correctly prints the letters when pressed (and does not print the Shift keys)
"""
def printKey(self, event):
# Adapted from http://www.kosbie.net/cmu/fall-10/15-110/koz/misc-demos/src/keyEventsDemo.py
ignoreSyms = [ "Shift_L", "Shift_R", "Control_L", "Control_R", "Caps_Lock" ]
if event.keysym not in ignoreSyms:
print event.char
def start(self):
self.root.mainloop()
def main():
a = App()
a.start()
if __name__ == "__main__":
sys.exit(main())https://stackoverflow.com/questions/9050282
复制相似问题