如何在tkinter窗口中显示当前日期

4

我正在尝试创建一个tkinter窗口,显示当前时间和日期,以及自定义短语。但问题在于,当天过去后无法刷新日期。

我可以传递代码运行时的当前日期,但之后就变为静态了。

以下是我的目前程序:

import tkinter as tk
import sys
import time
import calendar
import random
import datetime as dt
from tkinter import *


""" DICTIONARY PHRASES """
phrases = ["Phrase1", "Phrase2", "Phrase3"]




class Clock(tk.Label):
    """ Class that contains the clock widget and clock refresh """

    def __init__(self, parent=None, seconds=True, colon=False):
        """
        Create and place the clock widget into the parent element
        It's an ordinary Label element with two additional features.
        """
        tk.Label.__init__(self, parent)

        self.display_seconds = seconds
        if self.display_seconds:
            self.time     = time.strftime('%I:%M:%S %p')
        else:
            self.time     = time.strftime('%I:%M:%S %p').lstrip('0')
        self.display_time = self.time
        self.configure(text=self.display_time)

        if colon:
            self.blink_colon()

        self.after(200, self.tick)


    def tick(self):
        """ Updates the display clock every 200 milliseconds """
        if self.display_seconds:
            new_time = time.strftime('%I:%M:%S %p')
        else:
            new_time = time.strftime('%I:%M:%S %p').lstrip('0')
        if new_time != self.time:
            self.time = new_time
            self.display_time = self.time
            self.config(text=self.display_time)
        self.after(200, self.tick)


    def blink_colon(self):
        """ Blink the colon every second """
        if ':' in self.display_time:
            self.display_time = self.display_time.replace(':',' ')
        else:
            self.display_time = self.display_time.replace(' ',':',1)
        self.config(text=self.display_time)
        self.after(1000, self.blink_colon)



class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)            
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom


# Root is the name of the Tkinter Window. This is important to remember.
root=tk.Tk()

# Sets background color to black
root.configure(bg="black")

# Removes the window bar at the top creating a truely fullscreen
root.wm_attributes('-fullscreen','true')
tk.Button(root, text="Quit", bg="black", fg="black", command=lambda root=root:quit(root)).pack()

# this displays the clock know as clock1
clock1 = Clock(root)
clock1.pack()

# This gives the clock format.
clock1.configure(bg='black',fg='white',font=("helvetica",125))

# Gets date from host computer.
date = dt.datetime.now()
# Takes the date and formats it.
format_date = f"{date:%a, %b %d %Y}"

# Selects a random phrase from the phrases dictionary
phrase_print = random.choice(phrases)

# Add the date to the tkinter window
w = Label(root, text=format_date, fg="white", bg="black", font=("helvetica", 40))
w.pack()

# Add the phrase to the tkinter window
e = Label(root, text=phrase_print, fg="white", bg="black", font=("helvetica", 28))
e.pack()


root.mainloop()

就像我说的那样,它显示日期但只显示一次,然后就再也不会改变。

提前感谢你的帮助。

1个回答

4
更新失败的原因是,常量值被传递给了小部件w。我们需要更改这个问题,以便在每次更新时,小部件通过再次调用函数来更新日期。
删除此部分:
date = dt.datetime.now()
format_date = f"{date:%a, %b %d %Y}"
w = Label(root, text=format_date, fg="white", bg="black", font=("helvetica", 40))

将此替换为:

w = Label(root, text=f"{dt.datetime.now():%a, %b %d %Y}", fg="white", bg="black", font=("helvetica", 40))

1
谢谢!这很有帮助! - Megastrik3
非常抱歉,我很想帮忙,但是我的声望还不够高。 - Megastrik3
@Megastrik3 我的声望足够高,所以我给你加了10个声望,并给了moe 10个声望。两个问题都是值得的。 - WinEunuuchs2Unix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接