gpt4 book ai didi

python - Python 中按下按键时暂停和继续循环

转载 作者:行者123 更新时间:2023-12-02 08:53:48 27 4
gpt4 key购买 nike

谁能帮我解决这个问题?

按“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() 而不是 sleep 来捕获信号。

关于python - Python 中按下按键时暂停和继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60281502/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com