Tkinter:在循环中更新标签 [英] Tkinter: Updating Labels mid-loop

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

问题描述

我想将 GUI 中的标签更新为一种进度条,显示数据传输的完成程度.

I would like to update a Label in my GUI to be a sort of progress bar, display how complete a data transfer is.

无论我在哪里,人们都说要使用标签的 textvariable 选项,然后设置字符串和标签更新.这对我不起作用.标签在数据收集循环结束时更新.我对深度编程了解不多,但我想 Python 在完成数据收集循环而不是中间循环之后才会刷新 Tkinter.

Everywhere I look, people say to use the textvariable option of Label and then to set the string and the label updates. This does not work for me. The label updates at the end of the data collection loop. I don't know too much about programming in depth but I imagine that Python is not refreshing Tkinter until after it is finished with the data collection loop rather than mid loop.

这是数据收集循环:

def getdata(self, filename):
    data=[]
    count=0
    percentage=0
    self.ser.write('$get\r\n')
    total=int(self.ser.readline().split()[0])
    line=self.ser.readline()
    while line != '':
        data.append(line)
        count+= 1
        if percentage != str(round(float(count)/total,2)):
            menu.percentage.set(str(round(float(count)/total,2)*100)+'% Completed')

            #^^^menu.percentage is the textvariable of the Label I want updated^^^#

            print str(round(float(count)/total,2)*100)+'% Completed'
        percentage = str(round(float(count)/total,2))
        line=self.ser.readline()       
    outfile=open(filename, 'w')
    outfile.writelines(data)

我的问题是:是否有某种命令可以实时更新 GUI 中的标签?

My question is: Is there some sort of command that will update the Label in the GUI in realtime?

推荐答案

简短的回答是调用 update_idletasks.这是有效的,因为小部件更新是作为空闲任务处理的.这些通常由事件循环执行,但您可以将它们调用为小瓶 update_idletasks.

Short answer is to call update_idletasks. This works because widget updating is handled as an idle task. These normally get executed by the event loop but you can cause them to be called vial update_idletasks.

有关更多背景信息,请参阅问题的答案如何在 Tkinter 中更新小部件?,或者只是在此站点上搜索 update_idletasks.

For a little more background, see the answers to the question How do widgets update in Tkinter?, or just search for update_idletasks on this site.

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

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