[Tutor] Updating Label widgets in Tkinter

Blake.Garretson@dana.com Blake.Garretson@dana.com
Wed, 27 Feb 2002 12:28:08 -0500


>From: Tim Wilson <wilson@isis.visi.com>
>Subject: [Tutor] Updating Label widgets in Tkinter
>
>I'm working through a number of the Tkinter tutorials and John Grayson's
>book "Python and Tkinter Programming," but I continue to be stymied by
>the problem of updating the text of a label widget based on some
>calculation that's bound to a button. I'm including some code that draws
>a very simple screen that presents an entry widget. The user is supposed
>to enter a number, click calculate, and be presented with the square
>root of the number they typed. I've tried a bunch of things at this
>point, but everything's starting to blur. Can anyone point me in the
>right direction?

You are almost there.  Instead of assigning the text using the "text"
parameter, use the textvariable parameter and create another StringVar().
See the commented code below for the corrections.  The other thing I
changed is how you were calling self.calc.  The callbacks provided with
widgets don't let you pass variables to the functions as easily as a normal
function call.  You have to either use lambdas, or you can make the
variables accesible everywhere in the class by naming them self.whatever.

-Blake Garretson

###
from Tkinter import *
from math import sqrt

class Calculator(Frame):
    def __init__(self):
        """Create an instance of a very simple calculator."""
        Frame.__init__(self)
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Square Root Calculator')
        self.master.iconname('Sqrt')

        fInput = Frame(self)
        fInput.pack()
        Label(fInput, text='x = ').pack(side=LEFT)
        self.number = StringVar()        # Here I made the variable more
accesible
        Entry(fInput, textvariable=self.number).pack(side=LEFT)

        fOutput = Frame(self)
        fOutput.pack()
        fOutput.pack(padx=5, pady=5)
        self.result_var = StringVar()   # This is where I create the
StringVar that will define the text
        self.result_var.set('Waiting for a number...')
        result = Label(fOutput,
                       textvariable=self.result_var).pack(pady=10)

        buttons = Frame(self)
        buttons.pack(padx=5, pady=5)
        Button(buttons, text='Calculate',
               command=self.calc).pack(side=LEFT, padx=3)  # Note the
change in the callback
        Button(buttons, text='Quit',
               command=self.quit).pack(side=LEFT, padx=3)

    def calc(self):
        self.result_var.set("The square root of %s is %s" %
(self.number.get(),sqrt(float(self.number.get()))) )

Calculator().mainloop()