2

I want to make a timer which requiers space press to stop it. I also want to print out how much time has passed since the start of the loop. I tried this:

import msvcrt
import time

print("Press space")
start_time = time.time()
while True:
    # print how much time has passed
    print(start_time - time.time(), end='\r')

    # break the loop if space btn was pressed
    if msvcrt.getch() == b" ":
        break

But the problem is that the time passed will be printed only if I pressed a key, and I want it to print out continuesly. I tried this solution from https://stackoverflow.com/a/22391379/12132452, but because it was python 2, i kept getting this error

Traceback (most recent call last):
  File "f:/Projects/Python/test.py", line 9, in <module>
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
OSError: [WinError 10093] Either the application has not called WSAStartup, or WSAStartup failed

What do I need to do?

2 Answers 2

1

This might help:

import sys
import keyboard
import time

print("Press space")
start_time = time.time()
while True:
    try:

        print(start_time - time.time(), end='\r')
        if keyboard.is_pressed('SPACE'):
            print("\nyou pressed SPACE, exiting...")
            sys.exit()
    except:
        break
Sign up to request clarification or add additional context in comments.

2 Comments

ModuleNotFoundError: No module named 'keyboard'
Install it with python -m pip install keyboard
0

I know this question was answered, but here is another way of doing it in pygame:

import pygame
import time

pygame.init()

wn = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Timer')

start_time = time.time()

def main():
    running = True
    fps = 60
    clock = pygame.time.Clock()
    
    while running:
        clock.tick(fps)


        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        
        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE]:
            print(time.time() - start_time)
            running = False
        
        pygame.display.update()

main()

Also, to install pygame open a terminal and type:

python -m pip install pygame==1.9.6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.