【问题标题】:Python Recursion with Multiple Clocks具有多个时钟的 Python 递归
【发布时间】:2015-05-23 19:49:10
【问题描述】:

我正在尝试编写一个 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”循环会冻结界面。

【问题讨论】:

    标签: python loops recursion time


    【解决方案1】:

    这里的问题是无意递归:

    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 秒后执行。这可以防止它成为递归,也不会遇到堆栈溢出。

    【讨论】:

    • 谢谢@chepner,我已经习惯了turtle 的ontimer,以至于忘记了tkinter after 的界面更好。我已经更新了代码。
    猜你喜欢
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多