Tkinter function running even without clicking the button

Asked

Viewed 527 times

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 window "Result" appears soon even though I did not click on the button "btn". And why I need to import 'messagebox' separately even though I have imported every Tkinter module before?

1 answer

2


It is because you have already directly called the function in:

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

the command= being defined with the value of return of def add instead of the actual add in itself.

As the value of a and b probably that you want to be the same as, just do so (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 for integer:

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

or float if you wish to cast for floating, so

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.