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