0

I am trying to assign a different function to each of the headings on a tkinter treeview widget.

the following code has the inteded outcome, but is hardcoded:

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()

but when I try to make the same exact code, but use a for loop to set the column names and commands, each column's command is set to the last command in the loop:

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()

why is this happening? I know that a similar question has been answered in this post, but I would like to try to use the intended options if possible.

Jacob Long
  • 21
  • 2

1 Answers1

2

If I change

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

to

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

It seems to solve the issue

Jacob Long
  • 21
  • 2