为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英3389331 2023-06-06 15:09:40
我想运行一个循环来打印“Hello”,当我按“K”时它停止打印但它不会结束程序,然后当我再次按“K”时它会再次开始打印。我试过这个(使用键盘模块):import keyboardrunning = Truewhile running == True:    print("hello")    if keyboard.is_pressed("k"):        if running == True:            running = False        else:            running = True但是当我按下按钮时,它只是结束了程序,而这不是我想要做的。我明白它为什么会结束,但我不知道如何让它不结束。我怎样才能做到这一点?
查看完整描述

3 回答

?
开满天机

TA贡献1786条经验 获得超13个赞

import keyboard


running = True

display = True

block = False


while running:

    if keyboard.is_pressed("k"):

        if block == False:

            display = not display

            block = True

    else:

        block = False

    if display:

        print("hello")

    else:

        print("not")


查看完整回答
反对 回复 2023-06-06
?
万千封印

TA贡献1891条经验 获得超3个赞

也许是这样的:


import keyboard


running = True

stop = False


while !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")


查看完整回答
反对 回复 2023-06-06
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

您可以为按键使用一个处理程序,它设置一个事件,主线程可以定期测试该事件,并在需要时等待。


(请注意,这里有两种类型的事件,按键事件和 的设置running,因此不要将它们混淆。)


from threading import Event

from time import sleep

import keyboard


hotkey = 'k'


running = Event()

running.set()  # at the start, it is running


def 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 execution

keyboard.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')


查看完整回答
反对 回复 2023-06-06
  • 3 回答
  • 0 关注
  • 237 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信