如何在 Python 中暂停和恢复 while 循环?

我想运行一个循环来打印“Hello”,当我按“K”时它停止打印但它不会结束程序,然后当我再次按“K”时它会再次开始打印。


我试过这个(使用键盘模块):


import keyboard


running = True


while running == True:

    print("hello")

    if keyboard.is_pressed("k"):

        if running == True:

            running = False

        else:

            running = True

但是当我按下按钮时,它只是结束了程序,而这不是我想要做的。我明白它为什么会结束,但我不知道如何让它不结束。我怎样才能做到这一点?


慕桂英3389331
浏览 238回答 3
3回答

开满天机

import keyboardrunning = Truedisplay = Trueblock = Falsewhile running:    if keyboard.is_pressed("k"):        if block == False:            display = not display            block = True    else:        block = False    if display:        print("hello")    else:        print("not")

万千封印

也许是这样的:import keyboardrunning = Truestop = Falsewhile !stop:    if keyboard.is_pressed("k"):        running = !running          # Stops "hello" while    if keyboard.is_pressed("q"):        stop = !stop                # Stops general while    if running:        print("hello")

白衣染霜花

您可以为按键使用一个处理程序,它设置一个事件,主线程可以定期测试该事件,并在需要时等待。(请注意,这里有两种类型的事件,按键事件和 的设置running,因此不要将它们混淆。)from threading import Eventfrom time import sleepimport keyboardhotkey = 'k'running = Event()running.set()  # at the start, it is runningdef handle_key_event(event):    if event.event_type == 'down':        # toggle value of 'running'        if running.is_set():            running.clear()        else:            running.set()# make it so that handle_key_event is called when k is pressed; this will # be in a separate thread from the main executionkeyboard.hook_key(hotkey, handle_key_event)while True:    if not running.is_set():        running.wait()  # wait until running is set    sleep(0.1)            print('hello')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python