-1

A simple-looking Python function is bothering me. It is related to Tkinter. Look at the following code:

import tkinter as tk

class Mainwindow(tk.Tk):
    def __init__(self, title="No title", size = "500x300"):
        tk.Tk.__init__(self)
        self.title(title)
        self.geometry(size)

def btn_func(i):
    print(f"Button {i} is clicked")

root = Mainwindow()

buttons = []
for i in range(0, 2):
    buttons.append(  tk.Button(root, text = f"Button {i}", command = lambda : btn_func(i) )  )
    buttons[i].pack()

root.mainloop()

What I expected is that we see "Button 0 is clicked" when we click Button 0, and "Button 1 is clicked" when Button 1. But the result is always "Button 1 is clicked" regardless of what button I click. I can't figure out the wrong point in my code...

1 Answers1

1

After the loop, i is always 1. The btn_func does not use the i at the time it is defined, but at the time it is called. You will need to pass the actual i when defining your lambda. Try the following

import tkinter as tk
import time

class Mainwindow(tk.Tk):
    def __init__(self, title="No title", size = "500x300"):
        tk.Tk.__init__(self)
        self.title(title)
        self.geometry(size)

def btn_func(i):
    print(f"Button {i} is clicked")

root = Mainwindow()

buttons = []
for i in range(0, 2):
    buttons.append(  tk.Button(root, text = f"Button {i}", command = lambda i=i: btn_func(i) )  )
    buttons[i].pack()


root.mainloop()
Mitchell Olislagers
  • 1,758
  • 1
  • 4
  • 10