亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 267 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號