-2
from tkinter import *

a=float(input("a"))
b=float(input("b"))

def abc(x,y):
    print(x+y)

root=Tk()

b1=Button(root,text="add", command=abc(a,b))

b1.pack()

root.mainloop()

this is my code for a machine which can add two numbers when input from the user is taken and the button is pressed. but in this code the fucntion gets called and the output is printed i the terminal even when the button is not pressed. pls suggest the reason and the correction in the code. thanks

Ghantey
  • 626
  • 2
  • 11
  • 25

3 Answers3

1

Your solution might be this:

You can use lambda to create what is referred to as an anonymous function. In every way it's a function except it doesn't have a name. When you call the lambda command it returns a reference to the created function, which means it can be used for the value of the command option to the button.

from tkinter import *

a = float(input('Enter first value:')
b = float(input('Enter second value:')

root = Tk()

def abc(x,y):
    print x+y

b1 = Button(root, text='add', command=lambda: abc(a,b))
b1.pack()

root.mainloop()
Ghantey
  • 626
  • 2
  • 11
  • 25
  • code-only answers aren't very useful. It requires that we compare your code line-by-line and character-by-character to the original to see what changed. Even then, it doesn't help us understand _why_ you changed something. Your answer would be more useful if you explained what you changed and why. – Bryan Oakley Oct 22 '18 at 12:29
  • I have added some details why I had added lambda function – Ghantey Oct 22 '18 at 12:47
0

You have to use lambda for this task:

b1 = Button(root, text='add', command = lambda: abc(a,b))
Nouman
  • 6,947
  • 7
  • 32
  • 60
0

For the command parameter, you have to pass the function not to run it. It means you have to pass abc not abc(). When you pass abc(), the function is called automatically when you create your button. So you have 2 solutions:

Using lambda:

b1 = Button(root, text='add', command = lambda a,b: abc(a,b))

Or passing inputs in function parameters:

def abc(x=float(input('a')),y=float(input("y"))):
    print(x+y)

root=Tk()

b1=Button(root,text="add", command=abc)

b1.pack()

root.mainloop()
Mike - SMT
  • 14,784
  • 4
  • 35
  • 79