【问题标题】:How to update a label at a regular interval?如何定期更新标签?
【发布时间】:2017-09-28 22:34:02
【问题描述】:

这个问题对我来说似乎是出了名的顽固。

我正在尝试每秒更新一次标签(在下面的 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()

【问题讨论】:

  • 这类问题在这个网站上可能已经被问了一百次了。你做过研究吗?如果你这样做了,但你没有找到任何东西,你能分享你使用的搜索词吗?也许我们可以让这个问题的答案更容易找到。

标签: python button tkinter


【解决方案1】:

您不能在 GUI 中使用阻塞循环,因为它会阻塞 GUI 的循环。因此,它看起来像是被锁定了,因为您已阻止它响应。您需要使用 tkinters after 方法将代码添加到 GUI 主循环。

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”修复为“mins, secs”。

【讨论】:

  • 通配符导入并不“邪恶”,它们只是不是首选方式。
  • 除非他们邪恶的并且在你的梦中困扰着你。
  • 感谢所有的一切:一个有用的解释和一个完整的工作编码示例!
猜你喜欢
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 2015-12-08
相关资源
最近更新 更多