How to simulate a time trial with tkinter?

5

I'm developing a python game "Who wants to be a millionaire" and wanted to put in the game the "time trial" to appear the time while we answered the question and when the time is over and the question has not been answered the program ends "game over"

    
asked by anonymous 14.01.2015 / 16:47

1 answer

2

The example below counts down 60 seconds at the end of that time a message is displayed. To do this, use the after() method available in Tkinter , this method registers a callback that will be called after a certain time, once, to continue calling this callback you need to register it again within yourself to update the remaining time display.

Tkinter only ensures that callback is not called ahead of schedule, if the system is busy, there may be a longer delay.

#!/usr/bin/python

import Tkinter as tk

class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.wm_title("Quem quer ser um milionario")
        self.label = tk.Label(self, text="", width=40, height=5)
        self.label.pack()
        self.remaining = 0
        self.countdown(60) # Em segundos

    def countdown(self, remaining = None):
        if remaining is not None:
            self.remaining = remaining

        if self.remaining <= 0:
            self.label.configure(text="Game Over")
            # O tempo esgotou, fazer terminar o programa aqui
        else:
            self.label.configure(text="%d" % self.remaining)
            self.remaining = self.remaining - 1
            self.after(1000, self.countdown)

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

Font

It should not be difficult to implement this logic, you can create a boolean initialized variable as false, if the user answers the question you change the state of the variable to true. Here's an example:

answered = False
...
..

if self.remaining <= 0 and answered == False:
    self.label.configure(text="Game Over")
    # O tempo esgotou, fazer terminar o programa aqui
    
14.01.2015 / 17:23