【问题标题】:Change text on tkinter button during call back execution在回调执行期间更改 tkinter 按钮上的文本
【发布时间】:2016-03-06 10:36:27
【问题描述】:

我正在尝试在执行特定按钮的回调时更改按钮上的文本。

假设我的按钮上的文本是“运行”,我想在单击它之后以及在回调执行期间将其更改为“运行”。

回调执行完成后,我想改回“运行”。

我没有得到我的代码的哪一部分是错误的。

import Tkinter as tk
import time

root = tk.Tk()

def change():
    button.config(text='Running')
    button.config(state='disabled')
    print "start"
    time.sleep(5)
    print "end"
    button.config(state='normal')
    button.config(text="Run")

button = tk.Button(root,text="Run",command=change)
button.pack()


root.mainloop()

【问题讨论】:

    标签: python python-2.7 python-3.x tkinter sleep


    【解决方案1】:

    由于主循环的工作方式,睡眠使整个程序(包括界面)停止一段时间,通常会阻止它更改界面本身。

    在这里,试试.after 函数,应该可以正常工作。

    import Tkinter as tk
    import time
    
    root = tk.Tk()
    
    def change():
        button.config(text='Running')
        button.config(state='disabled')
        print "start"
        root.after(5000,changeback)
    def changeback():
        print "end"
        button.config(state='normal')
        button.config(text="Run")
    
    button = tk.Button(root,text="Run",command=change)
    button.pack()
    
    
    root.mainloop()
    

    root.after(5000,changeback) 将在5000 毫秒或 5 秒后调用命令而不停止整个程序,即changeback()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多