簡體   English   中英

python3 + tkinter:單擊時執行方法時未禁用按鈕

[英]python3 + tkinter: button isn`t disabled when a method is executed on click

我想使用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按鈕?

您正在錯誤地使用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()

我無法識別timer.Timer(),但是如果您想在配置中添加root.update()之后立即更改按鈕的狀態

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM