Blake Cook
Blake Cook

Reputation: 15

Is there a way to wait for a button to be pressed, but if button is not pressed then program returns?

So I am trying to to write a program in which the user in on a screen within Tkinter GUI, and want the system to start from the beginning if a physical button is not pressed.

def start():
    #creating instance
    window = Tk()


def btnclicked(): #ignore this name as its for another button
    def endgame():
        lbltitleend = Label(window, text="Press the button within 5 seconds to quit or the game will restart.", font=("Arial bold", 15), fg="white", bg="black", pady= 15)
        lbltitleend.pack()

        for objectx in objects:
            objectx.destroy()


        def buttonpress():
            while True:
                time.sleep(5)
                if (GPIO.input(22) == True):
                    window.destroy()
                    print("Thanks for playing!")
                    del objects[:]
                else:
                    start()


        window.after(500, buttonpress) # Need this so that the program doesnt stall waiting for button to be pressed, and executes everything before the button can be pressed

So this just ends up running and so after the 5 seconds of time.sleep it ends up just starting the program again and bringing up a new gui window which I don't mind, but it is not what I want.

What I want is for the program to be waiting for the button to be pressed and if not pressed within 5 seconds then I want it to restart.

Is there a way to do this?

Upvotes: 0

Views: 989

Answers (1)

Saad
Saad

Reputation: 3430

It is not that difficult as you already know about after() function, there is another function through which we can stop the processing of an after thread that is after_cancel(id). "id" is what the after() returns.

Here is an example of how you can stop before 5 secs complete.

from tkinter import *

root = Tk()
root.geometry('250x250')

display = Label(root, text='Hello', font=('', 20))
display.pack(pady=40)

def restart():
    display['text'] = 'Restarting...'
    but['state'] = 'disable'            # Once restarted the button gets disabled

def cancel():
    # Cancel the current after with it id
    root.after_cancel(L)
    display['text'] = 'Cancelled'

# Take a reference of after
L = root.after(5000, restart)

but = Button(root, text='Cancel', command = cancel )
but.pack(side='bottom', pady=30)

mainloop()

Hope this helped you.

Upvotes: 1

Related Questions