robertlugg / easygui

easygui for Python
http://easygui.readthedocs.org/en/master/
BSD 3-Clause "New" or "Revised" License
455 stars 114 forks source link

Can i limit the amount of time a user has to press a button #166

Open Gilf2121 opened 4 years ago

Gilf2121 commented 4 years ago

Can i limit the amount of time a user has to press a button?

spyoungtech commented 4 years ago

Per the documentation, EasyGUI is NOT event-driven, so this kind of functionality is not directly exposed by EasyGUI, but you can access some underlying Tkinter functionality to do this.

Namely, you could use the after callback for the underlying tkinter elements

Here is a complete example of a simple timed 'quiz' application.

'''Quiz with a 10 second timeout'''

import easygui as eg
import time

BOX = eg.buttonbox(msg="", title="QUIZ!", choices=['1','2','3'], run=False)

def timeout_poll(start, timeout=10):
    expires = start + timeout
    time_remaining = expires - time.time()
    if time_remaining <= 0:
        try:
            BOX.ui.boxRoot.destroy()
        except:
            pass
        eg.msgbox("TIME IS UP!")
        return
    message = f"What is 1 + 1? You have {timeout} seconds to choose!\n{time_remaining:0.0f} seconds remaining"
    BOX.msg = message
    BOX.ui.boxRoot.after(100, timeout_poll, start)

start = time.time()
BOX.ui.boxRoot.after(0, timeout_poll, start)
try:
    choice = BOX.run()
except:
    #if box was destroyed
    choice = None

if choice == '2':
    eg.msgbox(msg="Correct!", title="QUIZ")
else:
    eg.msgbox(msg="Sorry, try again!", title="QUIZ!")