[Tutor] Tab key in tkinter

Jim jf_byrnes at comcast.net
Wed Oct 23 22:20:55 EDT 2019


I needed to know the keycodes for the tab and return keys. When I was 
searching for them I came across this little program. I modified it to 
give me the keycodes. It seems to work with every key I tried except the 
tab key. I wonder why? The tab key does work in my editor.

# bind and show a key press event with Tkinter
# tested with Python24      vegaseat     20nov2006
from tkinter import *
root = Tk()
prompt = '      Press any key      '
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
def key(event):
     if event.char == event.keysym:
         msg = 'Normal Key %r' % event.keycode #event.char
     elif len(event.char) == 1:
         msg = 'Punctuation Key %r (%r)' % (event.keycode, event.char) 
  #(event.keysym, event.char)
         # added by me
         if event.keycode == 23:
             print('tab')
         else:
             print('nada')
     else:
         msg = 'Special Key %r' % event.keycode #event.keysym
         # added by me
         if event.keycode == 23:
             print('tab')
         else:
             print('nada')
     label1.config(text=msg)
root.bind_all('<Key>', key)
root.mainloop()

Thanks,  Jim



More information about the Tutor mailing list