Reputation: 61
I run this successfully in Python 2.7 with Pycharm IDE in one Macbook. I press arrow up key, event.char is not null, it can print out something. However, in the other Macbook or windows system, when I press keys which are not letters, it can not print out anything, all I see is "press: ". When I press letter key,it worked fine, and it print out the letters such like "press : A". Any thought is appreciated.
#
from Tkinter import *
#Entry
def printkey(event):
print('press:' + event.char)
#
root = Tk()
#input
entry = Entry(root)
#
entry.bind('<Key>', printkey)
#
entry.pack()
root.mainloop()
Upvotes: 2
Views: 5252
Reputation: 22804
In your code, event
is a Tkinter event object. This object has a short list of attributes, among them these 2 ones related to keyboard events (only):
char
: A single-character string that is the key's code keysym
: A string that is the key's symbolic nameThe later one is apparently what you are looking for.
You will find here a list enumerating the keysyms that will be recognized by Tk.
Other attributes of this event
Tkinter object:
num
: Button number (only for mouse-button events); 1 and upx
, y
: Mouse position, in pixels, relative to the upper left corner of the widgetx_root
, y_root
: Mouse position, in pixels, relative to the upper left corner of the screenwidget
: The widget in which the event has occurred.So your code should now look like this:
from Tkinter import *
#Entry
def printkey(event):
print('press:' + event.keysym)
#
root = Tk()
#input
entry = Entry(root)
#
entry.bind('<Key>', printkey)
#
entry.pack()
root.mainloop()
Upvotes: 4
Reputation: 799520
char
only contains a value when the key pressed corresponds to a character. If it does not then you will need to print or translate one of the other attributes, such as keysym
.
Upvotes: 2