按下 Python 中的键时暂停并继续循环

Pause and Continue a Loop When Press Key in Python

谁能帮我解决这个问题?

按"P"键暂停倒计时,按"S"键继续倒计时。直到现在我有这段代码,但我找不到解决这个问题的方法。

谢谢

from multiprocessing import Process
import keyboard
import time


def countdown_1():
    i=6
    j=40
    k=0
    while True:
        a = keyboard.read_key()

        if(str(a) != "p"):    
            if(j==-1):
                j=59
                i -=1
            if(j > 9):  

                print(str(k)+str(i)+":"+str(j))
            else:

                print(str(k)+str(i)+":"+str(k)+str(j))

            time.sleep(1)
            j -= 1
            if(i==0 and j==-1):
                break
    if(i==0 and j==-1):
        print("END")
        time.sleep(1)


countdown_1()

我得到了解决你问题的方法,那是因为当你使用 keyboard.readkey() python 等待按键被按下。相反,您应该使用 keyboard.is_pressed('X')

我已经修改了你的代码来制作一个工作版本,我稍微改变一下以符合我的口味。

from multiprocessing import Process
import keyboard
import time


def countdown_1():
    pause_keyboard = False  # I use a bolean as a state is clearer for me
    i = 6  # minutes
    j = 40
    k = 0  # represent 0 we will instead use code format

    while True:

        starting_time = time.time()

        while True:  # this loop wait one second or slightly more

            if time.time() - starting_time >= 1: #  a second or more
                break

            if keyboard.is_pressed('p'):
                pause_keyboard = True

            elif keyboard.is_pressed('s'):
                pause_keyboard = False

        if pause_keyboard:
            continue


        if (j == -1): ## here we adjust the count when we changes minutes

            j = 59  # 59 secondes
            i -= 1  # one minutes less

        if(j > 9):  ## in order to pretty print

            print("{}{}:{}".format(0, i, j))  # you can direclty use 0 instead of k.
        else:
            print("{}{}:{}{}".format(0, i, 0, j))

        j -= 1

        if(i==0 and j==-1):  # we finish the counter
            break

    if(i==0 and j==-1):
        print("END")
        time.sleep(1) # wait a last second


countdown_1()

编辑:使用 time.time() 而不是睡眠来捕获信号。