这个问题对我来说似乎是出了名的顽固。
我试图每秒更新标签(在while循环内的代码中称为lbl)。问题是标签没有更新。代码也没有抛出任何错误消息。
from tkinter import *
import tkinter
TIMER_START_MIN=5
TIMER_START_SEC=5*60
min,sec=divmod(TIMER_START_SEC,60)
banner_text="{:02d}:{:02d}".format(min,sec)
def timer_func():
global reset_button
global lbl
global TIMER_START_SEC
global banner_text
reset_button.config(state=tkinter.DISABLED)
while(TIMER_START_SEC>0):
mins,secs=divmod(TIMER_START_SEC,60)
banner_text="{:02d}:{:02d}".format(min,sec)
lbl.config(text=banner_text)
TIMER_START_SEC=TIMER_START_SEC-1
root=Tk()
top_frame=Frame(root)
top_frame.pack(side=TOP)
bottom_frame=Frame(root)
bottom_frame.pack(side=BOTTOM)
lbl=Label(top_frame,text=banner_text,font=('Helvetica', 36), fg='black')
lbl.grid(row=0,column=0)
start_stop_button=Button(bottom_frame,text="START",font=("Helvetica",24),command=timer_func)
start_stop_button.grid(row=0,column=0)
reset_button=Button(bottom_frame,text="RESET",font=("Helvetica",24))
reset_button.grid(row=0,column=1)
root.mainloop()
答案 0 :(得分:1)
您无法在GUI中使用阻塞循环,因为它会阻止GUI的循环。因此,由于您已将其阻止响应,因此它似乎已被锁定。您需要使用tkinters after
方法将代码添加到GUI mainloop。
import tkinter as tk
TIMER_START_MIN=5
TIMER_START_SEC=5*60
min,sec=divmod(TIMER_START_SEC,60)
banner_text="{:02d}:{:02d}".format(min,sec)
time_left = TIMER_START_SEC
def timer_start():
reset_button.config(state=tk.DISABLED)
timer_update()
def timer_update():
global time_left
if time_left > 0:
mins,secs=divmod(time_left, 60)
banner_text="{:02d}:{:02d}".format(mins,secs)
lbl.config(text=banner_text)
time_left -= 1
root.after(1000, timer_update)
root=tk.Tk()
top_frame=tk.Frame(root)
top_frame.pack(side=tk.TOP)
bottom_frame=tk.Frame(root)
bottom_frame.pack(side=tk.BOTTOM)
lbl=tk.Label(top_frame,text=banner_text,font=('Helvetica', 36), fg='black')
lbl.grid(row=0,column=0)
start_stop_button=tk.Button(bottom_frame,text="START",font=("Helvetica",24),command=timer_start)
start_stop_button.grid(row=0,column=0)
reset_button=tk.Button(bottom_frame,text="RESET",font=("Helvetica",24))
reset_button.grid(row=0,column=1)
root.mainloop()
我还摆脱了你的邪恶通配符导入并修复了更新功能中的拼写错误来自" min,sec"至"分钟,秒"。