Reputation: 101
I have this code that should run when the respective button is pressed, but nothing happens. Why would this be?
def keyReleased(self,event):
if event.keysym == 'Right':
self.move('Right')
elif event.keysym == 'Left':
direction= self.move('Left')
elif event.keysym == 'Up':
self.move('Up')
elif event.keysym =='Down':
self.move('Down')
elif event.keysym =='Escape':
self._root.destroy()
Upvotes: 1
Views: 12253
Reputation: 171
bind_all is one way to do it . Note that arrow keys are under the "special key" category for the code below.
try:
import Tkinter as tk ## Python 2.x
except ImportError:
import tkinter as tk ## Python 3.x
def key_in(event):
##shows key or tk code for the key
if event.keysym == 'Escape':
root.quit()
if event.char == event.keysym:
# normal number and letter characters
print'Normal Key', event.char
elif len(event.char) == 1:
# charcters like []/.,><#$ also Return and ctrl/key
print( 'Punctuation Key %r (%r)' % (event.keysym, event.char) )
else:
# f1 to f12, shift keys, caps lock, Home, End, Delete ...
print( 'Special Key %r' % event.keysym )
root = tk.Tk()
tk.Label(root, text="Press a key (Escape key to exit):" ).grid()
ent=tk.Entry(root)
ent.bind_all('<Key>', key_in) # <==================
ent.focus_set()
root.mainloop()
But if you only want the arrow keys then you can bind each one to a function
def arrow_down(event):
print "arrow down"
def arrow_up(event):
print "arrow up"
root = tk.Tk()
tk.Label(root, text="Press a key (Escape key to exit):" ).grid()
root.bind('<Down>', arrow_down)
root.bind('<Up>', arrow_up)
root.mainloop()
Upvotes: 1
Reputation: 369454
You should bind key event to the callback.
For example:
from Tkinter import * # Python 3.x: from tkinter import *
def hello(e=None):
print('Hello')
root = Tk()
Button(root, text='say hello', command=hello).pack()
root.bind('<Escape>', lambda e: root.quit())
root.bind('h', hello)
root.mainloop()
Upvotes: 1