【问题标题】:How to stop and continue the loop when pressing space bar?按下空格键时如何停止和继续循环?
【发布时间】:2022-11-21 19:57:35
【问题描述】:

我正在构建一个 Python 程序,该程序必须在用户按下“空格键”时运行(程序在用户已经按下“空格键”时运行),并且当他再次按下“空格键”时,程序停止(程序停止时用户不会再按一次“空格键”继续),等等! 而这一切都必须在里面

while True:

并包含一个

import keyboard

我的代码:

from pynput import keyboard
import time
import mouse
break_program = True
def main():
    mouse.move(800, 800, absolute=True, duration=3)
    time.sleep(3)
    mouse.move(800, 400, absolute=True, duration=3)
    time.sleep(3)
def on_press(key):
    global break_program
    print (key)
    if key == keyboard.Key.space and break_program:
        print ('end pressed')
        break_program = False

    if key == keyboard.Key.space:
        print ('enter pressed')
        break_program = True
print("Press 'SPACE' key to stop the bot.")
print("Press 'SPACE' to start the bot.")
listener =  keyboard.Listener(on_press=on_press)
listener.start()
while True:
    if break_program:
        main()
        time.sleep(1)

我希望你能帮我构建一个代码:用户按下“空格”键,软件运行。用户决定停止软件,于是他再次按下“空格”键(软件停止了)。例如,一个用户从休息回来并再次按下“空格”键(程序从他停止的同一点继续!(他没有退出程序!这是我想说的一点! ))

【问题讨论】:

    标签: python while-loop keyboard


    【解决方案1】:

    你想这样说:

    import keyboard
    from time import sleep
    while True:
        if keyboard.is_pressed('space'):
            break
        else:
            print('Doing stuff..')
            sleep(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-02
      • 2017-05-23
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      相关资源
      最近更新 更多