The calculator that I made has 2 entries , each one of them is supposed to hold a number and be stored in a variable , then when one of the buttons is pressed a window is supposed to pop out with the answer. The problem is it's giving me a blank window
from tkinter import *
from tkinter.messagebox import *
def addition():
showinfo("Message",(num1 num2))
def soust():
showinfo("Message",(num1-num2))
def multi():
showinfo("Message",num1*num2)
def divi():
showinfo("Message",num1/num2)
def annuler():
e1.delete(0,END)
e2.delete(0,END)
root= Tk()
root.title("Exemple 6")
nombre1 =Label(root,text="nombre1",background="green")
nombre1.pack()
e1=Entry(root)
e1.pack()
num1=e1.get()
nombre2= Label(root,text="nombre2",background="green")
nombre2.pack()
e2= Entry(root)
e2.pack()
num2=e2.get()
button1=Button(root,text=" ",command=addition,activebackground="red")
button1.pack(side=LEFT)
button2=Button(root,text=" - ",command=soust,activebackground="red")
button2.pack(side= LEFT)
button3=Button(root,text=" * ",command=multi,activebackground="red")
button3.pack(side=LEFT)
button4=Button(root,text=" / ",command=divi,activebackground="red")
button4.pack(side=LEFT)
button5=Button(root,text=" C ",command=annuler,activebackground="red")
button5.pack(side=LEFT)
root.mainloop()
I tried printing num1 and num2 but it gives this {}
CodePudding user response:
Your problem is that you are not taking the numbers you want at the time you want. The moment you read the values to num1 and num2 variables the value of e1 and e2 are both empty, so you reading empty to the variables.
You can easily solve your problem just reading the values of e1 and e2 right before make the operation.
Follow my corrections to your code:
from tkinter import *
from tkinter.messagebox import *
root= Tk()
root.title("Exemple 6")
nombre1 =Label(root,text="nombre1",background="green")
nombre1.pack()
e1=Entry(root)
e1.pack()
nombre2= Label(root,text="nombre2",background="green")
nombre2.pack()
e2= Entry(root)
e2.pack()
def get_nums():
return int(e1.get()),int(e2.get())
def addition():
num1,num2 = get_nums()
showinfo("Message",num1 num2)
def soust():
num1,num2 = get_nums()
showinfo("Message",num1-num2)
def multi():
num1,num2 = get_nums()
showinfo("Message",num1*num2)
def divi():
num1,num2 = get_nums()
showinfo("Message",num1/num2)
def annuler():
e1.delete(0,END)
e2.delete(0,END)
button1=Button(root,text=" ",command=addition,activebackground="red")
button1.pack(side=LEFT)
button2=Button(root,text=" - ",command=soust,activebackground="red")
button2.pack(side= LEFT)
button3=Button(root,text=" * ",command=multi,activebackground="red")
button3.pack(side=LEFT)
button4=Button(root,text=" / ",command=divi,activebackground="red")
button4.pack(side=LEFT)
button5=Button(root,text=" C ",command=annuler,activebackground="red")
button5.pack(side=LEFT)
root.mainloop()
And I get the expected results in my messagebox.