Tkinter等待按下按键

时间:2017-02-09 00:52:34

标签: python tkinter keyboard wait

我正在使用Python 3和Tkinter,我有一个wait()函数,等到按下右箭头键或左箭头键,然而,它只是冻结所有内容,我必须强制停止程序

from tkinter import *

right = left = False

def setLeft(event):
    global left
    left = True
    print('Left!')
def setRight(event):
    global right
    right = True
    print('Right!')

def wait():
    global right, left
    left = right = 0
    while not (left or right):
        pass
    print(right) #0 for left, 1 for right
    left = right = 0


root = Tk()
root.bind('<Left>', setLeft)
root.bind('<Right>', setRight)

wait()函数是否有办法像它应该的那样工作,或者我是否需要找到不同的方法?

1 个答案:

答案 0 :(得分:0)

是的,由于Tkinter GUI编程的事件驱动特性,您需要一种不同的方式。当某个事件引导您进入wait()函数时,它会:您陷入无限循环,并且您无法再进入事件了!

As @Bryan Oakley pointed - 默认情况下,GUI始终处于等待状态,因为您已达到mainloop()。而且我认为,当用户在树中导航时,你试图只是压制所有其他事件(或者只是导航键),除了这两个(左击和右击)。

所以这是一个小例子:

import tkinter as tk


# Main - application
class App(tk.Tk):
    # init of our application
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.minsize(width=450, height=100)
        self.wm_title('Just another example from SO')
        self.wait_state = False
        self.init_events()

    # switch state
    def switch_wait_state(self, event):
        self.wait_state = not self.wait_state
        print('Wait state switched to: %s ' % self.wait_state)

    # init events
    def init_events(self):
        self.bind('<Key>', self.wait)
        self.bind('<Control-s>', self.switch_wait_state)

    # waiter(listener) for keypress
    def wait(self, event):
        if self.wait_state and any(key == event.keysym for key in ['Left', 'Right']):
            print('I have successfully waited until %s keypress!' % event.keysym)
            self.do_smth(event.keysym)
        else:
            print('Wait state: %s , KeyPress: %s' % (self.wait_state, event.keysym))
            self.do_nhth()

    @staticmethod
    def do_smth(side):
        print("Don't be rude with me, Im trying my best on a %s side!" % side)

    @staticmethod
    def do_nhth():
        pass


app = App()
app.mainloop()