When I try to use the KeyRelease event on the Tkinter Text widget, it sometimes provides a lowercase character in event.char, but displays an uppercase character in the text widget. This occurs when I lightly and quickly press the shift button and then a letter. How can I reliably capture the correctly cased character with the KeyRelease event on a Tkinter Text widget?
Here’s the sample code that I tested on my MacBook Pro:
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())
What is happening is that you are releasing the shift key before the letter key. The shift is pressed at the time the character is inserted which is why the widget gets an uppercase character, but by the time your keyrelease binding is processed the shift has already been released so you see the lowercase character.
If you want to print what is being inserted, bind to the key press instead of the release.