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

查看:156
本文介绍了从变量更新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.

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

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.

推荐答案

仅在输入主循环后才显示该窗口.因此,您不会在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小部件的示例.当您在条目"小部件中更改文本时,它会在标签"中自动更改.

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

我喜欢以下参考: http://infohost.nmt.edu/tcc /help/pubs/tkinter/

以下是您要执行的操作的有效示例:

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天全站免登陆