Daniel Engel Daniel Engel - 3 months ago 14
Python Question

Something going wrong while making my progress bar in GUI

After I succeeded in making a progress bar in console, I thought about upgrading the program to GUI.

This is my code:

from tkinter import *
class Progress(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.value = 1
self.endvalue = 100
self.bar_length = 20

self.label1 = Label(self)
self.label1.grid()

self.button1 = Button(self, text = "Start", command = self.startprogress())
self.button.grid()
def startprogress(self):
while self.value <= self.endvalue:
root.after(100, self.updateprogress)
def updateprogress(self):
percent = float(self.value) / self.endvalue
arrow = '|' * int(round(percent * self.bar_length)-1) + '|'
spaces = ' ' * (self.bar_length - len(arrow))
self.label1.configure( text = "Percent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))) )
self.value+=1

root = Tk()
root.title("Progress")
app = Progress(root)
root.mainloop()


When I start the program, It does nothing; no error, no window going up.

I started debugging it, trying to understand the problem. If I erase all the code under the
__init__
function, the window would go up. For that I think maybe the
while
loop is the problem here.

Can someone tell me whats the problem in this program?

Answer

Look at this code:

def startprogress(self):
    while self.value <= self.endvalue:
        root.after(100, self.updateprogress)

This is an infinite loop. I hope I don't need to explain why.

What you probably wanted to do is this:

def startprogress(self):
    # queue ONE call to self.updateprogress
    root.after(100, self.updateprogress)

def updateprogress(self):
    percent = float(self.value) / self.endvalue
    arrow = '|' * int(round(percent * self.bar_length)-1) + '|'
    spaces = ' ' * (self.bar_length - len(arrow))
    self.label1.configure( text = "Percent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))) )
    self.value+=1

    # now that self.value has been incremented, queue ANOTHER call
    if self.value <= self.endvalue:
        root.after(100, self.updateprogress)