Search code examples
pythontimer

How can I make a timer where I press the space button or whatever key on the keyboard to stop the timer?


This is my Code:

seconds = 0
minuts = 0
while seconds > -1:
    rounded = round(seconds,2) 
    print(minuts,  'minutes,', rounded, 'seconds')
        
    seconds += 0.01
    time.sleep(0.01) 
    
    if rounded ==  59:
        s=0
        minuts+= 1

I want to press some key to stop the timer.


Solution

  • I have managed to make this work using the keyboard module in Python3 (detect key press in python?)

    This program simply loops the timer while the space key is not pressed, and stops when it is.

    import keyboard
    import time
    
    seconds = 0
    minutes = 0
    
    while not keyboard.is_pressed(" "):
        rounded = round(seconds, 2) 
        print(minutes,  'minutes,', rounded, 'seconds')
    
        seconds += 0.01
        time.sleep(0.01) 
    
        if rounded == 59:
            s = 0
            minutes += 1
    

    If you need the keyboard module, use pip install keyboard from the command line to install it.