具有多个时钟的Python递归

2024-04-26 03:41:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个Python程序,该程序具有同一类的多个标签,每个标签显示不同时区的时间,就像创建每个新实例时声明的那样。你知道吗

目前time_string_format是一个全球性的问题。我的想法是,通过在调用类之前更改全局值,可以为类的每个实例使用不同的字符串格式。你知道吗

这是一节课:

class winMain(Frame):
    def __init__(self, app):
        Frame.__init__(self, app)

        # establish the base font in a variable so it can be dynamically changes later
        self.base_font = "Times"
        self.base_font_size = int(38)

        # Create object lblDTG_ associated with variable lblDTG
        self.lblDTG = StringVar()
        lblDTG_ = Label(self, textvariable=self.lblDTG, text='lblDTG Not Set!', font=(self.base_font, self.base_font_size))
        lblDTG_.bind('<Double-Button-1>', self.onDoubleLeftClick)
        lblDTG_.bind('<Button-1>', self.onLeftClick)
        lblDTG_.bind('<Button-2>', self.onMiddleClick)
        lblDTG_.bind('<Button-3>', self.onRightClick)
        lblDTG_.pack(fill=X, expand=1)

        # start the clock
        time_format = time_string_format
        self.set_time(time_format)

    def set_time(self, time_format):
        # update the DTG
        self.lblDTG.set(datetime.datetime.utcnow().strftime(time_format).upper())

现在,时间是在类创建时设置的,但从未更新过。我可以像下面这样使用递归,但是当超过递归深度时,我最终会遇到堆栈错误:

def set_time(self, time_format):
            # update the DTG
            self.lblDTG.set(datetime.datetime.utcnow().strftime(time_format).upper())
            self.after(1000, self.set_time(time_format)

有没有什么方法可以使用迭代来实现这一点?当时钟运行时,我仍然希望能够通过绑定改变时区、字符串格式等来与它们交互。我担心使用“for”或“while”循环会冻结接口。你知道吗


Tags: theself程序formatbasedatetimetimebind
1条回答
网友
1楼 · 发布于 2024-04-26 03:41:51

这里的问题是一个不谨慎的递归:

def set_time(self, time_format):
            # update the DTG
            self.lblDTG.set(datetime.datetime.utcnow().strftime(time_format).upper())
            self.after(1000, self.set_time(time_format)

最后一行应该是这样的:

self.after(1000, self.set_time, time_format)

set_time的调用不应该像当前编写的那样现在执行,而是从现在开始执行1秒。这使它不会成为递归,也不会经历堆栈溢出。你知道吗

相关问题 更多 >