我有这个代码应该在按下相应的按钮时运行,但没有任何反应。为什么会这样?
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()
答案 0 :(得分:1)
您应该将键事件绑定到回调。
例如:
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()
答案 1 :(得分:1)
bind_all是一种方法。请注意,箭头键位于以下代码的“特殊键”类别下。
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()
但是如果你只想要箭头键,那么你可以将每个键绑定到一个函数
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()