【问题标题】:How do you create a while true loop while still keeping a tkinter page open?如何在保持 tkinter 页面打开的同时创建一个 while true 循环?
【发布时间】:2020-03-13 18:21:37
【问题描述】:

我正在尝试创建一个显示时间的 tkinter 页面,并且应该不断更新。我试过了:

from tkinter.font import *
import time
def SetTime():
    global time_date
    time_date = time.strftime("%H:%M")
    InfoTime.set(time_date)
Main = Tk()
Main.geometry("1600x1200")
Main.title("Time")
FontStyle = Font(family = "Times New Roman", size = 48)
InfoTime = StringVar()
TitleText = Label(Main,textvariable = InfoTime,font = FontStyle).pack()
while True:
    SetTime()

但是,运行 While True: 线路和运行 SetTime() 由于某种原因,不断地阻止 tkinter 页面(主)打开。这对我的许多 tkinter 项目来说都是一个问题。

请注意,我在 IDLE 中运行 python 3.7.2。 谢谢。

【问题讨论】:

    标签: loops tkinter python-3.7


    【解决方案1】:

    应该这样做:

    from tkinter import *
    from tkinter.font import *
    import time
    
    Main = Tk()
    Main.geometry("1600x1200")
    Main.title("Time")
    
    FontStyle = Font(family = "Times New Roman", size = 48)
    TitleText = Label(Main, font = FontStyle)
    TitleText.pack()
    
    time_date1 = ''
    
    def SetTime():
        global time_date1
        global TitleText
    
        # Gets current time
        time_date2 = time.strftime("%H:%M")
        # If time has changed, update it
        if time_date2 != time_date1:
            time_date1 = time_date2
            TitleText.config(text=time_date2)
    
        # Repeats function every 200 milliseconds 
        TitleText.after(200, SetTime)
    
    SetTime()
    Main.mainloop()
    

    cmets 几乎可以解释一切。我还清理并重新格式化了您的代码以使其看起来更好。

    【讨论】:

      猜你喜欢
      • 2022-08-23
      • 1970-01-01
      • 2020-07-15
      • 2014-07-30
      • 2020-05-31
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多