Rohan K.
Rohan K.

Reputation: 91

Label widget problems

I am having problems in my Tkinter project. I am trying to create a simple addition calculator that only computes two numbers and. I am having trouble creating the addition function. I want to create a label that displays the variable 'finalans' which is basically the value of the sum of the two digits that the user inputs in the Entry Box Widgets.

def Addition():
    top = Toplevel()

    top.geometry("500x500")

    global finalans

    #First Entry

    e = Entry(top)
    e.pack()

    e.focus_set()

    #Function for finding answer
    def Answer():

        firstval = int(e.get())
        secondval = int(m.get())
        finalans = firstval + secondval

        #Final Answer
        answer = Label(top, textvariable=finalans)
        answer.pack()

    h = Label(top, text="First Numeric Value")
    h.pack()

    #Second Entry
    m = Entry(top)
    m.pack()

    m.focus_set()

    z = Label(top, text="Second Numeric Value")
    z.pack()

    add2 = Button(top, text="Submit", width=10, command=Answer)
    add2.pack()

    mainloop()

When I try to run the program and display the answer using the Label widget the label does not display anything at all. There isn't even an error code or anything in the console. How do I make the Label Widget display the variable?

Upvotes: 0

Views: 51

Answers (1)

furas
furas

Reputation: 142899

First finalans have to be StringVar().
Second use finalans.set(string) to change it.

And you could create answer label only once.

def Addition():
    top = Toplevel()

    top.geometry("500x500")

    global finalans

    finalans = StringVar()

    #First Entry

    e = Entry(top)
    e.pack()

    e.focus_set()

    #Function for finding answer
    def Answer():

        firstval = int(e.get())
        secondval = int(m.get())
        finalans.set( str(firstval + secondval) )

    h = Label(top, text="First Numeric Value")
    h.pack()

    #Second Entry
    m = Entry(top)
    m.pack()

    m.focus_set()

    z = Label(top, text="Second Numeric Value")
    z.pack()

    add2 = Button(top, text="Submit", width=10, command=Answer)
    add2.pack()

    #Final Answer
    answer = Label(top, textvariable=finalans)
    answer.pack()

    mainloop()

Addition()

Upvotes: 1

Related Questions