Home > Enterprise >  how to add two numbers in tkinter
how to add two numbers in tkinter

Time:02-07

I am trying to learn tkinter. I have written a code to add two numbers and show the result below. But I get an error. Anybody can let me know where I have a mistake? Thank you

This is my code:

from tkinter import *

root = Tk()
root.geometry("400x400")

label1 = Label(root, text="your first number:").grid(row=0, column=0)
label2 = Label(root, text="your second number:").grid(row=1, column=0)

first_no  = IntVar()
second_no = IntVar()

entry1 = Entry(root, textvariable = first_no).grid(row=0, column=1)
entry2 = Entry(root, textvariable = second_no).grid(row=1, column=1)

def add():
    sumation = first_no.get()   second_no.get()
    label3.config(text = "your final number is:"   str(sumation))
    
mybutton = Button(root, text="Calculate!", command = add).grid(row=2, column=1)

label3 = Label(root).grid(row=3, column=1)

root.mainloop()

and this is the error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\pymnb\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "<ipython-input-13-6c227c88abbc>", line 17, in addition
    label3.config(text = "your final number is:"   str(sumation))
AttributeError: 'NoneType' object has no attribute 'config'

CodePudding user response:

It errors bc .grid doesnt return the label. so do it two steps

from tkinter import *

root = Tk()
root.geometry("400x400")

Label(root, text="your first number:").grid(row=0, column=0)
Label(root, text="your second number:").grid(row=1, column=0)
# define the label, step 1
label3 = Label(root)
# set grid, step 2
label3.grid(row=3, column=1)

first_no = IntVar()
second_no = IntVar()

# same goes for here
entry1 = Entry(root, textvariable=first_no).grid(row=0, column=1)
entry2 = Entry(root, textvariable=second_no).grid(row=1, column=1)


def add():
    sumation = first_no.get()   second_no.get()
    label3.config(text="your final number is:"   str(sumation))

# and here
mybutton = Button(root, text=("Calculate!"), command=add).grid(row=2, column=1)

root.mainloop()

CodePudding user response:

You forget to instance label3:

label3 = Label(root, text="result:").grid(row=3, column=0)

Because of that this line is returning "NoneType"

label3.config(text="your final number is:"   str(sumation))
  •  Tags:  
  • Related