【问题标题】:Is there a way to wait for a button to be pressed, but if button is not pressed then program returns?有没有办法等待按钮被按下,但如果按钮没有被按下,那么程序返回?
【发布时间】:2019-04-26 20:52:35
【问题描述】:

所以我正在尝试编写一个程序,其中用户在 Tkinter GUI 中的屏幕上,如果没有按下物理按钮,则希望系统从头开始。

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

所以这只是最终运行,所以在 time.sleep 5 秒后它最终只是再次启动程序并打开一个新的 gui 窗口,我不介意,但这不是我想要的。

我想要的是让程序等待按钮被按下,如果在 5 秒内没有按下,那么我希望它重新启动。

有没有办法做到这一点?

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    after() 函数并不像您已经知道的那么难,还有另一个函数可以通过它停止处理after 线程,即after_cancel(id)。 “id”是 after() 返回的内容。

    这是一个如何在 5 秒完成前停止的示例。

    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()
    

    希望这对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多