tkinter, overwrite Label-text?

Bryan Oakley oakley at bardo.clearlight.com
Fri Apr 11 11:11:37 EDT 2008


skanemupp at yahoo.se wrote:
> ok but i have trouble using grid. if i try to use a Label witht he
> text answer in the following code it doenst work very well.
> 

Can you describe "have trouble"? What sort of trouble -- syntax errors, 
the text never shows up, etc?

Following is my attempt to use a label and textvariables for both the 
label widget and the entry widget. Caveat emptor: I've *never* written a 
tkinter program before in my life. I'm a tcl/tk expert but I'm learning 
python and this is my very first attempt.

I took the liberty to reorganize the code slightly. There are still 
resize behaviors I don't like but let's tackle one problem at a time 
(rest assured: the problems are all solvable).

Does this do what you want?

from __future__ import division
import Tkinter
from Tkinter import *

def main():
     root = Tkinter.Tk()
     makeUI(root)
     root.mainloop()
     exit()

def makeUI(root):
     global entryVariable
     global displayVariable

     displayVariable = StringVar()
     entryVariable = StringVar()

     root.title("Calculator")
     entry = Entry(root, textvariable=entryVariable)
     entry.grid(row=1, column=1, columnspan=4, sticky="nsew")

     display=Label(root, textvariable=displayVariable)
     display.grid(row=2, column=1, columnspan=4, stick="nsew")

     x = 1
     y = 4
     for char in '123+456-789*0()/.':
         b = Button(root, text=char, command=lambda n=char:Disp(n),
                    width=2, height=1)
         b.grid(row=y, column=x)
         x=x+1
         if x==5:
             x=1
             y=y+1

     b = Button(root, text="^", command=lambda n="**":Disp(n),
                width=2,height=1)
     b.grid(row=8, column=2)
     b = Button(root, text="C",command=Erase, width=2, height=1)
     b.grid(row=8, column=3)
     b = Button(root, text="c",command=Backspace, width=2, height=1)
     b.grid(row=8, column=4)
     b = Button(root, text="=",command=Calc, width=18, height=1)
     b.grid(row=9, column=1, columnspan=8)

def Disp(nstr):
     global entryVariable
     tmp=entryVariable.get()
     tmp+=nstr
     entryVariable.set(tmp)

def Calc():
     global entryVariable
     global displayVariable

     expr=entryVariable.get()
     displayVariable.set("")
     try:
         displayVariable.set(eval(expr))
     except:
         displayVariable.set("Not computable")

def Erase():
     global entryVariable
     global displayVariable

     entryVariable.set("")
     displayVariable.set("")

def Backspace():
     global entryVariable
     tmp=entryVariable.get()
     tmp=tmp[0:-1]
     entryVariable.set(tmp)

main()



More information about the Python-list mailing list