[Tutor] Updating Label widgets in Tkinter

Tim Wilson wilson@isis.visi.com
Tue, 26 Feb 2002 23:21:07 -0600 (CST)


Hi everyone,

I'm hoping there's a Tkinter expert or two out there who can offer some
help with the following:

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?

Here's the code. Thanks.

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)
        number = StringVar()
        Entry(fInput, textvariable=number).pack(side=LEFT)
        
        fOutput = Frame(self)
        fOutput.pack()
        fOutput.pack(padx=5, pady=5)
        result = Label(fOutput, 
                       text='Waiting for a number...').pack(pady=10)

        buttons = Frame(self)
        buttons.pack(padx=5, pady=5)
        Button(buttons, text='Calculate', 
               command=self.calc(number)).pack(side=LEFT, padx=3)
        Button(buttons, text='Quit', 
               command=self.quit).pack(side=LEFT, padx=3)

    def calc(self, number):
        """Update the label named 'result' to say 'The square root of 
        <insert original number> is <square root of that number>' 
        and then clear the contents of the entry box."""
                
Calculator().mainloop()

--
Tim Wilson      |   Visit Sibley online:   | Check out:
Henry Sibley HS |  http://www.isd197.org   | http://www.zope.com
W. St. Paul, MN |                          | http://slashdot.org
wilson@visi.com |  <dtml-var pithy_quote>  | http://linux.com