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 a
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.
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))