简体   繁体   English

Python进度条GUI

[英]Python progress bar GUI

I wonder if you can help me. 我想知道您是否能帮助我。 I have seen code for creating a progress bar GUI and am trying to modify it slightly so that I can send the progress bar the value I want it to be. 我已经看到了用于创建进度条GUI的代码,并且正在尝试对其进行一些修改,以便可以将所需的值发送给进度条。 Below is my code 下面是我的代码

import tkinter as tk
from tkinter import ttk
import time

class progress_bar(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.progress = ttk.Progressbar(self, orient="horizontal", length=200, mode="determinate")
        self.progress.pack()
        self.val = 0
        self.maxval = 1
        self.progress["maximum"] = 1

    def updating(self, val):
        self.val = val
        self.progress["value"] = self.val
        print(self.val)

        if self.val == self.maxval:
            self.destroy()

def test():
    for i in range(0, 101):
        time.sleep(0.1)
        app.updating(i/100)

app = progress_bar()
app.after(1, test)
app.mainloop()

When I run the code the print message progresively increases from 0 - 1 as expected, however while the GUI is created it remains empty until the program has finished and it closes as required. 当我运行代码时,打印消息按预期方式从0-1逐渐增加,但是在创建GUI时,它保持为空,直到程序完成并根据需要关闭为止。 Can you tell me what I need to modify so the GUI updates please. 您能告诉我我需要修改什么以便GUI更新吗? Thanks in advance for any help provided. 在此先感谢您提供的任何帮助。

The issue you're having is that your test function blocks the tkinter event loop. 您遇到的问题是您的test功能会阻止tkinter事件循环。 That means that even though the progress bar's value gets updated, the progress never appears on the screen (since nothing gets redrawn until test ends). 这意味着即使进度条的value被更新,进度也永远不会出现在屏幕上(因为直到test结束才重绘任何内容)。

To fix this, you need to get rid of the loop in test and instead use tkinter code to do the repeated updates. 要解决此问题,您需要摆脱test中的循环,而应使用tkinter代码进行重复更新。

Here's a modified version of test that should work: 这是应该可以使用的test的修改版本:

def test(i=0):
    app.updating(i/100)
    if i < 100:
        app.after(100, test, i+1)

Rather than explicitly looping, it reschedules itself every 100 milliseconds. 它不是显式循环,而是每100毫秒重新安排自己的时间。 Rather than i being a loop variable, it is now an argument, and each scheduled call gets a larger i value than the one before it. 现在, i不再是一个循环变量,而是一个自变量,并且每个计划调用都将获得比之前更大的i值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM