1

I am making a Who Wants to be a Millionare game in Python using graphics. I want the user to get 45 seconds per question to answer it. However, whenever I put a timer in my code it waits for 45 seconds first, then lets the user answer, instead of running in the background and letting the user answer at the same time.

Matthew
  • 99
  • 1
  • 2
  • 10
python geek
  • 41
  • 1
  • 1
  • 3
  • Post the code that is giving you problems. – derricw Jan 16 '16 at 01:00
  • 1
    Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your code and accurately describe the problem. StackOverflow is not a coding or tutorial service. – Prune Jan 16 '16 at 01:19

2 Answers2

6

Using the threading module to run multiple threads at once

You could use the Python threading module to make two things happen at once, thereby allowing the user to answer while the timer ticks down.

Some example code utilizing this:

from threading import Thread
from time import sleep
import sys

def timer():
    for i in range(45):
        sleep(1)   #waits 45 seconds
    sys.exit() #stops program after timer runs out, you could also have it print something or keep the user from attempting to answer any longer

def question():
    answer = input("foo?")

t1 = Thread(target=timer)
t2 = Thread(target=question)
t1.start() #Calls first function
t2.start() #Calls second function to run at same time

It's not perfect, but this code should start two different threads, one asking a question and one timing out 45 seconds before terminating the program. More information on threading can be found in the docs. Hope this helps with your project!

Community
  • 1
  • 1
Matthew
  • 99
  • 1
  • 2
  • 10
  • so i put my code inside the question function and called it but it says main thread is not in main loop... – python geek Jan 17 '16 at 01:41
  • Apparently, if you are using graphics, the code controlling the graphics must be in the main thread. Perhaps try starting the question thread before the timer thread? If you are using Python 3.4 or above, try `assert threading.current_thread() == threading.main_thread()` to check if one thread is the main thread. Also see [this question](http://stackoverflow.com/questions/14694408/runtimeerror-main-thread-is-not-in-main-loop) and/or [this question](http://stackoverflow.com/questions/23206787/check-if-current-thread-is-main-thread-in-python). – Matthew Jan 17 '16 at 18:45
-4

Try using time.time(). This returns a the amount of seconds since January 1, 1970 in UNIXTime. You can then create a while loop such that:

initial_time = time.time()
while time.time()-initial_time < 45:
    #Code

Hope this helped!