【问题标题】:python3 + tkinter: button isn`t disabled when a method is executed on clickpython3 + tkinter:单击时执行方法时不会禁用按钮
【发布时间】:2017-10-07 15:36:16
【问题描述】:

我想用 tkinter 写一个简单的计时器。 我有一个开始按钮:

start_button = tkinter.Button(root, bg="white", text="Start", command=start_button_clicked)

以及在点击时运行的命令

def start_button_clicked():
    start_button.config(text='Started', state='disabled')
    tm = timer.Timer()
    tm.count_time(1)

我希望它会发生

  1. 更改按钮文本和状态
  2. 创建新计时器并运行倒计时

但实际上按钮参数只有在定时器用完后才会改变。 为什么会这样?如何在点击后立即更改 bu 按钮?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    我无法识别 timer.Timer(),但是如果您想在配置后立即更改按钮的状态,请添加 root.update()

    def start_button_clicked():
        start_button.config(text='Started', state='disabled')
        root.update()
        tm = timer.Timer()
        tm.count_time(1)
    

    【讨论】:

    • Its my own custom Timer. So this is no surprise it doesnt 工作。您的建议很有帮助,谢谢!
    【解决方案2】:

    您错误地使用了 Timer() 函数。您可以尝试使用“时间”库或使用time.delay(10) 创建计时器。但是,如果您想使用Timer(),您可以执行以下操作:

    from threading import Timer
    from tkinter import *
    
    
    def disable_button():
        start_button.config(text='Started', state='disabled')
    
    def start_button_clicked():
        tm = Timer(3, disable_button)
        tm.start()
    
    root = Tk()
    root.minsize(100, 100)
    
    start_button = tkinter.Button(root, bg="white", text="Start", command=start_button_clicked)
    start_button.pack()
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      相关资源
      最近更新 更多