How to simulate a time trial with Tkinter?

Asked

Viewed 454 times

4

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

1 answer

1

The example below makes a countdown of 60 seconds at the end of that time is displayed a message. To make it work the method is used after() available on Tkinter, this method records a function callback who will be called after a certain time, only once, to continue calling that callback you need to re-register it within you to update the remaining time display.

Tkinter only guarantees that the callback is not called ahead of schedule, if the system is busy, there may be a further 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()

Source

It shouldn’t be difficult to implement this logic, you can create a variable boolean initialized as false, if the user answers the question you change the state of the variable to true. See 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
  • thanks staff resulted in perfection :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.