Tkinter and PMW - dynamic labels

Christopher T King squirrel at WPI.EDU
Thu Jul 29 16:16:55 EDT 2004


On Thu, 29 Jul 2004, uri bushey wrote:

> Is there an easy way to have a label read from a variable, and update 
> itself when the variable is changed?

You can do this by using a StringVar.  Try this in an interactive session:

>>> from Tkinter import *
>>> w = Tk()
>>> v = StringVar()
>>> l = Label(textvariable = v)
>>> l.pack()
>>> v.set('Hello!')	# label will read "Hello!"
>>> v.set('Goodbye!')	# label will read "Goodbye!"
>>> e = Entry(textvariable = v)
>>> e.pack()		# now whatever is typed in the Entry widget
			# will instantly appear in the Label
>>> e.get()		# will return text currently in Entry widget

IntVar and DoubleVar provide similar functionality for ints and floats, 
respectively.  Other widgets provide a similar 'variable' option to allow 
them to directly interact with variables.

Unfortunately the Var classes don't play well with normal Python 
operations; you must always access them through their .set() and .get() 
methods.

> I have the label, and I have a Python megawidget (pmw) PromptDialog that 
> gets a value from the user. I would like that value to update the label 
> - is there a way to do that without creating and destroying the label in 
> a function that is called every time the PromptDialog is called?

Yes, you can simply change the label's text attribute:

 mylabel['text'] = newvalue

Hope this helps.




More information about the Python-list mailing list