0

I have been trying to create multiple buttons in tkinter library (with numbers as text), using for loop. And i want to print the text of each button every time i click one. Like a calculator. But the problem is that it prints only the last line in the loop.

win=tk.Tk()
def butt(x):
    print(x)
for i in range(1,4):
    bt=tk.Button(win,text=i,command=lambda: butt(i));bt.pack()
win.mainloop() 

One solution of this that i found is to write lambda i=i : ... but i dont understand what this is. Thank you for your time!!

fizz fish
  • 41
  • 5

2 Answers2

0

Lambda expression here returns the method that prints the i value.

import tkinter as tk

win=tk.Tk()

def get_print_method(x):
    def print_i():
        print(x)
    return print_i

for i in range(1,4):

    bt=tk.Button(win, text=i, command=get_print_method(i))
    bt.pack()

win.mainloop() 

Lambda in your case is an equivalent of the get_print_method function.

Benjamin
  • 3,217
  • 2
  • 27
  • 42
0

This a well-known behavior in Python for lambda

This happens because i is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined

Python FAQ on lambdas

Their solution, is to give lambda a default parameter

import tkinter as tk
win=tk.Tk()
def butt(x):
    print(x)
for i in range(1,4):
    bt=tk.Button(win,text=i,command=lambda j=i: butt(j))
    bt.pack()

#i = 'This is now a string'

win.mainloop()
Space
  • 142
  • 1
  • 7