How do you implement a Progress Bar

Alf P. Steinbach alfps at start.no
Sat Feb 13 02:54:21 EST 2010


* J Wolfe:
> I would really appreciate some help with this.  I'm fairly new to
> using classes...What am I doing wrong? All I get is a blank window. I
> can't seem to figure out how to initialize this Progress Bar.
> 
> Thanks,
> Jonathan
> 
> 
> 
> ##############################file Meter.py####################
> from Tkinter import *
> 
> class Meter(Frame):
> 	'''A simple progress bar widget.'''
> 	def __init__(self, master, fillcolor='orchid1', text='',value=0.0,
> **kw):
> 		Frame.__init__(self, master, bg='white', width=350,height=20)
> 		self.configure(**kw)
> 		self._c = Canvas(self, bg=self['bg'],width=self['width'],
> height=self['height'],highlightthickness=0, relief='flat',bd=0)
> 		self._c.pack(fill='x', expand=1)
> 		self._r = self._c.create_rectangle(0, 0, 0, int(self['height']),
> fill=fillcolor, width=0)
> 		self._t = self._c.create_text(int(self['width'])/2,
> int(self['height'])/2, text='')
> 		self.set(value, text)
> 
> 	def set(self, value=0.0, text=None):
> 		#make the value failsafe:
> 		if value < 0.0:
> 			value = 0.0
> 		elif value > 1.0:
> 			value = 1.0
> 		if text == None:
> 		#if no text is specified get the default percentage string:
> 			text = str(int(round(100 * value))) + ' %'
> 			self._c.coords(self._r, 0, 0, int(self['width']) * value,
> int(self['height']))
> 			self._c.itemconfigure(self._t, text=text)
> 
> 
> 
> root=Tk()
> f=Meter(root)

At his point the Meter widget has been created, but it's still invisible.

To make it visible you have to register it with a layout manager (in 
tkinter-speak a "geometry" manager).

A layout manager for a widget X is responsible for placing child widgets of X.

The easiest is to add, at this point,

   f.pack()

which uses the packing layout manager of the parent widget of f (not sure why 
the design is like this, but f.pack() forwards up to the parent's layout 
manager). You can add various optional parameters. Or use other layout mgr.

Take care that all child widgets of a given parent widget use the same layout 
manager, otherwise the typical result is a hang.


> for i in range(100):
> 	f.set(i,"Hello")
> 	print i

This will probably happen too fast to see, before the window is presented.

One idea might be to add a few buttons for testing things.


> mainloop()


Cheers & hth.,

- Alf



More information about the Python-list mailing list