stringvariable.set 将字符串从 Python 函数传输到 Tkinter 的方法

stringvariable.set method to transfer a string into Tkinter from a Python function

我正在遵循一种巧妙的方法(基于 "Whosebug" 和其他地方给出的代码示例,用于在包含许多框架页面的 Tkinter 应用程序周围传输 datetime.utcnow 内容。我使用的方法是在每个帧上定义一个一致命名的时间标签对象,并在第一个(主页)帧上声明全局 time1 和 time1=tk.StringVar()。我的函数生成一个包含使用 strftime 方法格式化的时间戳的字符串如下图

time1=datetime.utcnow()
time1=time1.strftime('%Y-%m-%d %H:%M:%S')
time1=('Time: ' + time1)

def second_tick():
    global time2, time1, stroke_time
    current_time = datetime.utcnow()
    current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
    time2 = ('Time: ' + current_time)
    if time2 != time1:
        time1.set(time2)
        time1=time2
        print(time2, current_time[14:19])
# calls itself every 200 milliseconds (5 times a second)
app.after(200, second_tick)

当我 运行 此代码失败并显示以下消息时: time1.set(时间2) AttributeError: 'str' 对象没有属性 'set'

然而,当我将函数简化为代码下方的形式时 运行s 完美:

def second_tick():
    global time2, time1, stroke_time
    current_time = datetime.utcnow()
    current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
    time2 = ('Time: ' + current_time)
    time1.set(time2)
    print(time2, current_time[14:19])
    # calls itself every 200 milliseconds (5 times a second)
    app.after(200, second_tick)

我想使用以前的版本来减少以高于一秒的速率刷新屏幕的需要(以及其他原因)。任何人都可以解释为什么 time1.set(time2) 指令在简化版本而不是首选版本中工作。 先感谢您, 奥利弗

time1=datetime.utcnow()
time1=time1.strftime('%Y-%m-%d %H:%M:%S')
time1=('Time: ' + time1)
#also in second_tick as well
time1=time2

在这些行中,您将 time1 更改为 string。不要以这种方式分配它,而是将 StringVars 值设置为该字符串。

time1.set('Time: ' + datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'))

编辑:his/her 自身问题的 OP 解决方案(取自评论)

time2=datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') 
def second_tick(): 
    global time2, time3, stroke_time 
    time3=datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') 
    if time3 != time2: 
        time1.set('Time: ' + time3) 
        time2=time3 
        print(time2, time3) 
    # calls itself every 200 milliseconds (5 times a second) 
    app.after(200, second_tick)