1

我有这段代码应该在按下相应的按钮时运行,但没有任何反应。为什么会这样?

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

2 回答 2

1

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()
于 2013-10-09T07:32:25.713 回答
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()
于 2013-10-09T18:01:50.380 回答