Reputation: 189
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. 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. Can you tell me what I need to modify so the GUI updates please. Thanks in advance for any help provided.
Upvotes: 0
Views: 4342
Reputation: 104852
The issue you're having is that your test
function blocks the tkinter
event loop. 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).
To fix this, you need to get rid of the loop in test
and instead use tkinter
code to do the repeated updates.
Here's a modified version of test
that should work:
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. 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.
Upvotes: 2