Python Tkinter treeview.heading 命令在 for 循环中无法正常工作

Python Tkinter treeview.heading command not working right in for loop

我正在尝试为 tkinter 树视图小部件上的每个标题分配不同的功能。

以下代码具有预期的结果,但是是硬编码的:

from tkinter import *
from tkinter.ttk import *

root = Tk()

treeview = Treeview(root, columns=['c1', 'c2'])
treeview.pack()


treeview.heading('c1', text='c1', command=lambda:print('c1'))
treeview.heading('c2', text='c2', command=lambda:print('c2'))


root.mainloop()

但是当我尝试编写完全相同的代码,但使用 for 循环来设置列名和命令时,每列的命令都设置为循环中的最后一个命令:

from tkinter import *
from tkinter.ttk import *

root = Tk()

treeview = Treeview(root, columns=['c1', 'c2'])
treeview.pack()


for c in ['c1', 'c2']:
    treeview.heading(c, text=c, command=lambda:print(c))


root.mainloop()

为什么会这样?我知道 中已经回答了类似的问题,但如果可能的话,我想尝试使用预期的选项。

如果我改变

for c in ['c1', 'c2']:
    treeview.heading(c, text=c, command=lambda:print(c))

for c in ['c1', 'c2']:
    treeview.heading(c, text=c, command=lambda col=c:print(col))

似乎解决了问题