On clicking the numbers to input it onto the entry widget, it always adds 10 rather than the number supposed to

Question:

for i in range(1,4):
    for j in range(3):
        button = tk.Button(text=str(num+1),master=window,padx=40,pady=20,command=lambda:button_click(num+1))
        button.grid(row=i,column=j)
        num+=1


def button_click(Number):
    ent_number.insert(tk.END,Number)

Whenever I click any button, which shows the appropriate numbers i.e 1,2,3,etc. it always inserts 10 to the entry widget.

Answers:

You can easily solve your problem by making num a default parameter:

lambda num=num: button_click(num)

Why does this work?

A pre-defined variable in a function could either be a parameter or a global variable. The first preference goes to the function parameter.

For example, if you execute the below code, it will print out 10, not 6.

def func(num):
    print(num)
    
num = 6
func(10)

In your code, when you use lambda:button_click(num+1), num is considered a global variable and the value of num is always 10 irrespective of which button triggered the event.

However, when num is passed as a parameter, the parametric value doesn’t change with iterations of the loop. When the function is executed, the parametric value of num is considered, which depends on the source button.

Answered By: Sriram Srinivasan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.