从变量更新 Tkinter 标签 [英] Update Tkinter Label from variable

查看:20
本文介绍了从变量更新 Tkinter 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 Python 脚本,它执行一些生成任务,然后不断更改一些存储为字符串变量的文本.这有效,我可以在每次更改时打印字符串.

I wrote a Python script that does some task to generate, and then keep changing some text stored as a string variable. This works, and I can print the string each time it gets changed.

我可以让标签第一次显示字符串,但它永远不会更新.

I can get the Label to display the string for the first time, but it never updates.

这是我的代码:

from tkinter import *

outputText = 'Ready'
counter = int(0)

root = Tk()
root.maxsize(400, 400)

var = StringVar()

l = Label(root, textvariable=var, anchor=NW, justify=LEFT, wraplength=398)
l.pack()

var.set(outputText)

while True:
    counter = counter + 1
    outputText = result
    outputText = result
    outputText = result
    if counter == 5:
        break

root.mainloop()

标签将显示 Ready,但不会更新以将其更改为稍后生成的字符串.

The Label will show Ready, but won't update to change that to the strings as they're generated later.

经过相当多的谷歌搜索并查看本网站上的答案后,我认为解决方案可能是使用 update_idletasks.每次更改变量后,我都尝试将其放入,但没有帮助.

After a fair bit of googling and looking through answers on this site, I thought the solution might be to use update_idletasks. I tried putting that in after each time the variable was changed, but it didn't help.

推荐答案

该窗口仅在进入 mainloop 后显示.因此,您不会在 root.mainloop() 行之前的 while True 块中看到您所做的任何更改.

The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True block preceding the line root.mainloop().

GUI 界面通过在主循环中对事件做出反应来工作.这是一个示例,其中 StringVar 也连接到 Entry 小部件.当您更改 Entry 小部件中的文本时,它会自动更改 Label 中的文本.

GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.

from tkinter import *

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

t = Entry(root, textvariable = var)
t.pack()

root.mainloop() # the window is now displayed

我喜欢以下参考:tkinter 8.5 参考:Python 的 GUI

这是您尝试执行的操作的有效示例:

Here is a working example of what you were trying to do:

from tkinter import *
from time import sleep

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

for i in range(6):
    sleep(1) # Need this to slow the changes down
    var.set('goodbye' if i%2 else 'hello')
    root.update_idletasks()

root.update 进入事件循环,直到 Tcl 处理完所有挂起的事件.

root.update Enter event loop until all pending events have been processed by Tcl.

这篇关于从变量更新 Tkinter 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆