如何通过诸如 之类的按键来打破这个循环Esc?此示例捕获击键,但从未将变量传递到 while 循环中。from pynput import keyboardcount = 0stop = 0while True: def press_callback(key): if key == keyboard.Key.esc: def stop_loop(): stop = 1 return stop print('You pressed "escape"! You must want to quit really badly...') stop = stop_loop() return stop count +=1 print (count) if stop == 1: break if count == 1: l = keyboard.Listener(on_press=press_callback) l.start()我使用的是 Ubuntu 18.04。
2 回答
暮色呼如
TA贡献1853条经验 获得超9个赞
stop_loop像这样更新你的方法:
def stop_loop():
global stop
stop = 1
return stop
如果您不声明,那么您将在方法内创建一个新的局部变量global stop,而不是更新在文件开头定义的变量。stopstopstop_loop
芜湖不芜
TA贡献1796条经验 获得超7个赞
这是最终的工作解决方案:
from pynput import keyboard
count = 0
stop = 0
def press_callback(key):
if key == keyboard.Key.esc:
def stop_loop():
global stop
stop = 1
return stop
print('Get Out')
stop = stop_loop()
return stop
l = keyboard.Listener(on_press=press_callback)
l.start()
while True:
count += 1
print (count)
if stop == 1:
break
添加回答
举报
0/150
提交
取消