J.C. J.C. - 7 months ago 9
Python Question

Cannot print out "event.char" using Tkinter

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()

Answer

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 name

The 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 up
  • x, y: Mouse position, in pixels, relative to the upper left corner of the widget
  • x_root , y_root: Mouse position, in pixels, relative to the upper left corner of the screen
  • widget: 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()