如何设置标签使其不断返回时间值

时间:2018-01-13 20:41:33

标签: python tkinter tk python-datetime

我正在尝试设置一个简单的python应用程序,它会以HH:MM:SS格式告诉时间,我会设置一个表示时间的变量,另一个表示使用strftime的格式化时间,并创建一个可以不断返回它的标签。由于我现在实现了datetime而不是datetime,因此表示小时(应该)的值会不断变化。但我不知道如何使标签更新(最好与小时更改同步)。我设法得到了一个不完整的解决方案,通过使用" whiletrue"为整个程序创建一个循环。声明,但它唯一做的就是在我关闭前者时显示另一个带有更新时间的窗口。我还查看了论坛中的其他帖子,告诉我使用after()函数,但程序返回一个错误,表示它不识别配置。这是我的代码:

while True:
    from datetime import *
    from tkinter import *
    window = Tk()
    window.title = ('Hour')
    #Implementation of a derived class defining tz

    class montréal(tzinfo) :
        _offset = timedelta(seconds = -18000)
        _name = "-0500"
        _dst = timedelta(0)        
        def utcoffset(self, dt):
            return self.__class__._offset
        def tzname(self, dt):
            return self.__class__._name
        def dst(self, dt):
            return self.__class__._dst
        def fromutc(self, dt):
        # raise ValueError error if dt.tzinfo is not self
            dtoff = dt.utcoffset()
            dtdst = dt.dst()
        # raise ValueError if dtoff is None or dtdst is None
            delta = dtoff - dtdst  # this is self's standard offset
            if delta:
                dt += delta   # convert to standard local time
                dtdst = dt.dst()
                # raise ValueError if dtdst is None
            if dtdst:
                return dt + dtdst
            else:
                return dt

    tz = montréal()

    actualTime = datetime.now(tz)

    #Defining the parameters for the new template

    actualHour = actualTime.strftime('%H')

    actualMinute = actualTime.strftime('%M')

    actualSecond= actualTime.strftime('%S')

    #Setting the template in a human-understandable way

    hourTemplate = actualHour,':',actualMinute,':',actualSecond

    hour= StringVar()

    hour.set(hourTemplate)

    #setting the Label widget 

    cadran = Label(window, textvariable=hour).pack(padx = 300, pady = 20)

    def hour_after():
        hour_updated = actualTime
        cadran.config(textvariable=hour_updated)
        window.after(1000,hour_after)

    hour_after()

    #closing statement
    window.mainloop()

我收到的错误信息如下:

Traceback (most recent call last):
  File "/Users/louiscouture/Documents/heure.py", line 62, in <module>
    hour_after()
  File "/Users/louiscouture/Documents/heure.py", line 59, in hour_after
    cadran.config(textvariable=hour_updated)
AttributeError: 'NoneType' object has no attribute 'config'

1 个答案:

答案 0 :(得分:0)

常见错误

cadran = Label().pack()

您将None分配给cadran,因为pack()会返回None

你必须分两行

cadran = Label()
cadran.pack()

编辑工作代码(但我不知道您在课程__class__中使用Montreal的原因)

import tkinter as tk
import datetime

# --- classes --- (CamelCaseNames without native chars)

class Montreal(datetime.tzinfo) :

    _offset = datetime.timedelta(seconds = -18000)
    _name = "-0500"
    _dst = datetime.timedelta(0)        

    def utcoffset(self, dt):
        return self.__class__._offset

    def tzname(self, dt):
        return self.__class__._name

    def dst(self, dt):
        return self.__class__._dst

    def fromutc(self, dt):
        # raise ValueError error if dt.tzinfo is not self
        dtoff = dt.utcoffset()
        dtdst = dt.dst()
        # raise ValueError if dtoff is None or dtdst is None
        delta = dtoff - dtdst  # this is self's standard offset
        if delta:
            dt += delta   # convert to standard local time
            dtdst = dt.dst()
            # raise ValueError if dtdst is None

        if dtdst:
            return dt + dtdst
        else:
            return dt


# --- functions ---

def hour_after():
    actualTime = datetime.now(tz)
    cadran['text'] = actualTime.strftime('%H:%M:%S')
    window.after(1000, hour_after)

# --- main ---

tz = Montreal()

window = tk.Tk()
window.title = 'Hour' # you don't need `( )`

cadran = tk.Label(window)
cadran.pack(padx=300, pady=20)

hour_after()

window.mainloop()