Search code examples
pythonuser-inputpygame-clock

Timed user input in Python


I am trying to take user input in Python with a timer. I want the user to only have 10 seconds to enter something. However when 10 seconds is over the message "Time up!" is printed but the script does not stop.

import pygame
from threading import Thread

clock = pygame.time.Clock()
timee = 0
UIn=None

def func1():
    global timee
    global clock
    global UIn
    while True:
        milli = clock.tick()
        seconds = milli/1000

        timee=timee+seconds
        if(int(timee)==10):
            print("Time is over")
            quit()
        

def func2():
    global UIn
    print("Working")
    input("Press key:\t")


Thread(target=func1).start()
Thread(target=func2).start()
UIn=input("Press key:\t")

Solution

  • You can use the Timer class for this purpose

    from threading import Timer
    
    timeout = 10
    t = Timer(timeout, print, ['Sorry, times up!'])
    t.start()
    prompt = "You have %d seconds to answer the question. What color do cherries have?...\n" % timeout
    answer = input(prompt)
    t.cancel()
    

    Output:

    You have 10 seconds to answer the question. What color do cherries have?
    (After 10 seconds)
    Sorry, times up!