I'm making a simple calculator with tkinter, the calculation part is fine. The problem is the variable (answer) not getting updated after calculation.
You can see in the window, result label is empty as it's initial value. tkinter window
This is the code I used:
from tkinter import *
import tkinter.messagebox as messagebox
answer=""
root = Tk()
root.geometry("600x300")
root.title("Simple Calculator")
def calculate():
value_1 = value_1_entry.get()
operator = operator_entry.get()
value_2 = value_2_entry.get()
if operator==' ':
answer = float(value_1_entry.get()) float(value_2_entry.get())
print(answer)
elif operator=='-':
answer = float(value_1_entry.get()) - float(value_2_entry.get())
print(answer)
return answer
##################Labels###############
value_1 = Label(root, text='Enter first value', font=('bold', 10))
value_1.place(x=20, y=30)
value_1_entry = Entry()
value_1_entry.place(x=150, y=30)
operator = Label(root, text='Enter the operator', font=('bold', 10))
operator.place(x=20, y=60)
operator_entry = Entry()
operator_entry.place(x=150, y=60)
value_2 = Label(root, text='Enter second value', font=('bold', 10))
value_2.place(x=20, y=90)
value_2_entry = Entry()
value_2_entry.place(x=150, y=90)
#################Results####################
result = Label(root, text='Result:', font=('bold', 10))
result.place(x=20, y=120)
result_ = Label(root, text=answer, font=('bold', 10))
result_.place(x=150, y=120)
##################Buttons###############
calculate = Button(root, text="calculate", font=("bold",10), bg="white", command=calculate)
calculate.place(x=70, y=140)
# Run
root.mainloop()
I cant figure out how to make answer="" get updated to new answer in tkinter window, result label.
CodePudding user response:
You can update label text using Label.config() method
.
Syntax : Label.config(text = your_text)
result_.config(text=answer)
in your case for example:
if operator == ' ':
answer = float(value_1_entry.get()) float(value_2_entry.get())
elif operator == '-':
answer = float(value_1_entry.get()) - float(value_2_entry.get())
result_.config(text=answer)
CodePudding user response:
Simply update the label inside calculate()
:
def calculate():
value_1 = value_1_entry.get()
operator = operator_entry.get()
value_2 = value_2_entry.get()
answer = None
if operator==' ':
answer = float(value_1_entry.get()) float(value_2_entry.get())
elif operator=='-':
answer = float(value_1_entry.get()) - float(value_2_entry.get())
if answer:
print(answer)
result_['text'] = answer # update result_ label
return answer