daylight72
daylight72

Reputation: 1

How do I make a button to execute and display calculation using variables entered in "Entry" in Python using the tkinter module?

I want to be able to execute the calculation x + y when the button SOLVE is click.

With how I have done it, I still have to input values for x and y in the console instead of in the entry block and upon clicking the SOLVE button, it returns :

"TypeError : unsupported operand type(s) for +: 'NoneType' and 'NoneType'

Code:

import tkinter
from tkinter import *

window = tkinter.Tk()
window.title("SOLVE MATH")

def solve_now():
    x= tkinter.Label(window, text="X").pack()
    X = tkinter.Entry(window, text=int(input("Enter X value: 
"))).pack()
    y = tkinter.Label(window, text="Y").pack()
    Y = tkinter.Entry(window, text=int(input("Enter Y value: 
"))).pack()
    ans = X + Y
    tkinter.Label(window, text=ans).pack()

tkinter.Button(window, text="SOLVE", 
command=solve_now).pack()


window.mainloop()

Upvotes: 0

Views: 925

Answers (1)

AD WAN
AD WAN

Reputation: 1474

This how to get values in tkinter entry to do calculation on it.For you to achieve that you have to create entry widget then use get function to retrieve the value in the entry to do your calculations. Read more about entry widget here entry widget

Using input will let you type you value in the console. You are getting Nonetype error because you have to position your geometry manager pack on the next line after the entry widget function.

entry1 = Entry(window )
entry1.pack()

Full code

import tkinter
from tkinter import *


def solve_now():
    ans = float(float(entry1.get()) + float(entry2.get()))
    print(ans)
    l3.config(text="Answer : "+str(ans))



window = tkinter.Tk()
window.title("SOLVE MATH")

l1 = Label(window, text="Enter Value X")
l1.pack()
entry1 = Entry(window, )
entry1.pack()


l2 = Label(window, text="Enter value Y")
l2.pack()
entry2 = Entry(window)
entry2.pack()

b1 = Button(window, text="SOLVE",
command=solve_now)
b1.pack()


l3 = Label(window)
l3.pack()

window.mainloop()

Upvotes: 1

Related Questions