【问题标题】:Tkinter button function doesn't work properlyTkinter 按钮功能无法正常工作
【发布时间】:2020-12-28 09:36:04
【问题描述】:

我有一个从按钮调用的函数。它有一个 time.sleep()

def func():
    button.place_forget()
    text = Label(root, text = "Text"
    text.place(x = 0, y = 0, in_ = root)
    time.sleep(1)
    text.place_forget()

button = Button(root, text = "Button", command = func)

当它被调用时,我希望按钮首先消失,然后文本出现,然后等待 1 秒钟,然后文本消失。但是会发生什么是程序等待 1 秒然后添加文本立即将其删除,然后使按钮消失。如何让它按我想要的方式工作?

【问题讨论】:

  • 您可以尝试将您的command 更改为command=lambda:func()

标签: python tkinter button


【解决方案1】:

使用after() 代替sleep()

def func():
    button.place_forget()
    text = Label(root, text="Text")
    text.place(x=0, y=0)
    # schedule to remove the text after 1 second
    text.after(1000, text.place_forget)

【讨论】:

    【解决方案2】:
    button = Button(root, text = "Button", command = func())
    button.pack()
    

    【讨论】:

    • command=func() 将立即执行func(),而不是在单击按钮时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    相关资源
    最近更新 更多