Friday, January 1, 2016

Python tkinter progress bar

Google keeps bringing me the same four examples for how to do a tkinter progress bar. It turns out that one of them is good in that a commenter showed how to implement a progress bar screen as a class which is how my entire project is constructed. Here's the link:

http://stackoverflow.com/questions/7310511/how-to-create-downloading-progress-bar-in-ttk

I reformatted the commenter's very helpful example to make the window quit when 100% is reached. I had to feel my way around how to add the quit and the destroy; I tried making a root object from the launch of Tk() and using it's quit and destroy, but for some reason that didn't work like it did in my other display classes. So in the end, here is my slightly modified version of the original program:

import Tkinter as tk
import ttk


class SampleApp(tk.Tk):

def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
##root = self.root = tk.Tk()
##root.title('root title')
self.button = ttk.Button(text="start", command=self.start)
self.button.pack()
self.progress = ttk.Progressbar(self, orient="horizontal",
length=200, mode="determinate")
self.progress.pack()

self.bytes = 0
self.maxbytes = 0
def start(self):
self.progress["value"] = 0
self.maxbytes = 50000
self.progress["maximum"] = 50000
self.read_bytes()
def read_bytes(self):
'''simulate reading 500 bytes; update progress bar'''
self.bytes += 500
self.progress["value"] = self.bytes
if self.bytes < self.maxbytes:

# read more bytes after 100 ms
self.after(100, self.read_bytes)
else:
self.quit()
app = SampleApp()
app.mainloop()
app.destroy()