如何使用 Esc 停止 while 循环?

如何通过诸如 之类的按键来打破这个循环Esc?此示例捕获击键,但从未将变量传递到 while 循环中。


from pynput import keyboard

count = 0

stop = 0

while 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。


蓝山帝景
浏览 116回答 2
2回答

暮色呼如

stop_loop像这样更新你的方法:def stop_loop():  global stop  stop = 1  return stop如果您不声明,那么您将在方法内创建一个新的局部变量global stop,而不是更新在文件开头定义的变量。stopstopstop_loop

芜湖不芜

这是最终的工作解决方案:from pynput import keyboardcount = 0stop = 0def 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    
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python