【发布时间】:2018-01-13 20:41:32
【问题描述】:
我正在尝试设置一个简单的 python 应用程序,它会以 HH:MM:SS 格式告诉时间,为此我设置了一个表示时间的变量和另一个表示使用 strftime 格式化时间的变量,并创建一个会不断返回它的标签。由于我现在实施日期时间而不是今天的日期时间,因此代表小时的值(应该)不断变化。但我不知道如何让标签本身更新(最好与小时变化同步)。通过使用“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'
【问题讨论】:
-
错误显示
cadran是None所以你必须检查你在哪里分配None到cadran -
在
while中导入是没有意义的,因为 Python 只会导入一次 - 而且可读性较差。使用while True一次又一次地创建Tk()也没有任何意义。 -
顺便说一句:在
from datetime import *和(其他导入)中使用*不是首选 - 这就是我使用import datetime和datetime.tzinfo的原因
标签: python tkinter tk python-datetime