J.C.
J.C.

Reputation: 61

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

Upvotes: 2

Views: 5252

Answers (2)

Billal BEGUERADJ
Billal BEGUERADJ

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

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

Related Questions