Reputation: 57
Who can help me on this?
Pause Countdown when press "P" Key and continue the Countdown when press "S" key. Until now i have this code, but i cant find the way to solve this.
Thanks
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()
Upvotes: 4
Views: 4451
Reputation: 1014
I get a solution to your problem, that is because when you use keyboard.readkey() python wait for a key to be pressed. instead, you should use keyboard.is_pressed('X')
I have modified your code to make a working version, I slightly change it to match my taste.
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()
EDIT: Use time.time() instead of sleep to be able to catch signals.
Upvotes: 2