Reputation: 23
i want to make a button on which '2' is written .... now when anyone click it , it will show the number '2' in the entry box... the error is: before clicking , it is already showing '2' in the entry box
So please help me removing this error here is my program
from tkinter import *
root = Tk()
def add(x):
e1=Entry(root)
e1.insert(INSERT, x)
e1.pack()
a=Button(root, text='2', command=add(2))
a.pack()
root.mainloop()
Upvotes: 1
Views: 675
Reputation: 368954
Pass a function (used lambda
in the following code) instead of return value of the function.
from tkinter import *
root = Tk()
e1 = Entry(root)
e1.pack()
def add(x):
e1.insert(INSERT, x)
a = Button(root, text='2', command=lambda: add(2))
a.pack()
root.mainloop()
In addition to that, extract Entry creation code out of the add
function. Otherwise entry are create every time when the button is clicked.
Upvotes: 2
Reputation: 121966
When you do:
a=Button(root, text='2', command=add(2))
it is the same as:
add(2)
a=Button(root, text='2', command=None)
i.e. you are calling add
and assigning its return
value to command
. Instead, you can use functools.partial
to create a function that will call add
with the argument 2
:
from functools import partial
a=Button(root, text='2', command=partial(add, 2))
Upvotes: 1