Tkinter function being executed even without clicking the button

0

Here is my code:

from tkinter import *
from tkinter import messagebox
def add(a, b):
    messagebox.showinfo("Resultado", a.get()+b.get())
win=Tk()
win.geometry('300x200')
a=StringVar()
b=StringVar()
in1=Entry(win, textvariable=a)
in2=Entry(win, textvariable=b)
btn=Button(win, text="Somar", activebackground='green', command=add(a,b))
in1.pack()
in2.pack()
btn.pack()
win.mainloop()

When I run the "Result" window it appears right away without clicking the "btn" button. And why do I need to import 'messagebox' separately even though I have imported all tkinter modules before?

    
asked by anonymous 13.02.2018 / 18:18

1 answer

2

It's because you've already called the function directly in:

btn=Button(win, text="Somar", activebackground='green', command=add(a,b))

command= is being set to the value of return of def add instead of add itself.

Since the value of a and b is likely to be the same as, just do this (since a and b are in the larger scope):

from tkinter import *
from tkinter import messagebox

def add():
    messagebox.showinfo("Resultado", a.get()+b.get())

win=Tk()
win.geometry('300x200')
a=StringVar()
b=StringVar()
in1=Entry(win, textvariable=a)
in2=Entry(win, textvariable=b)
btn=Button(win, text="Somar", activebackground='green', command=add)
in1.pack()
in2.pack()
btn.pack()
win.mainloop()

However, note that a.get() and b.get() return strings and when using the + will only concatenate, so use int if you want to cast integer:

def add():
    messagebox.showinfo("Resultado", int(a.get()) + int(b.get()) )

or float if you want to cast the float, so

def add():
    messagebox.showinfo("Resultado", float(a.get()) + float(b.get()) )
    
13.02.2018 / 18:45