【问题标题】:How to set up a label so it return the time value constantly [duplicate]如何设置标签使其不断返回时间值[重复]
【发布时间】: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'

【问题讨论】:

  • 错误显示cadranNone 所以你必须检查你在哪里分配Nonecadran
  • while 中导入是没有意义的,因为 Python 只会导入一次 - 而且可读性较差。使用while True 一次又一次地创建Tk() 也没有任何意义。
  • 顺便说一句:在 from datetime import * 和(其他导入)中使用 * 不是首选 - 这就是我使用 import datetimedatetime.tzinfo 的原因

标签: python tkinter tk python-datetime


【解决方案1】:

常见错误

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()

【讨论】:

    猜你喜欢
    • 2021-07-08
    • 2021-08-23
    • 2017-09-22
    • 2021-05-15
    • 2017-07-04
    • 2018-12-23
    • 2020-02-12
    • 2022-07-14
    • 2016-08-22
    相关资源
    最近更新 更多