问题描述
我正在使用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楼
是的,由于Tkinter GUI编程的事件驱动性质,您需要使用其他方法。
当某个事件将您引向您的wait()
函数时,它就是:您陷入无限循环,并且您再也无法摆脱事件!
正如@Bryan Oakley -默认情况下,由于您到达了mainloop()
,因此GUI始终处于等待状态。
而且我认为,您尝试仅在用户浏览树时抑制所有其他事件(或仅浏览键),但不包括这两个事件(左键和右键单击)。
所以这是一个小例子:
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()