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

Jacob Long

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Tkinter Treeview heading styling

Why my for loop isn't working right for the menus in tkinter python

tkinter button created in loop command not working

How to edit the style of a heading in Treeview (Python ttk)

Horizontal Scrollbar for TreeView not working in Tkinter

Python Tkinter for loop checkbuttons not working as intended

Right Click Menu on Tkinter Treeview widget

Python tkinter button command dont runing right parameter

Python Tkinter button command doesn't run the right parameter

Tkinter/Python Treeview change header

Python tkinter treeview column sizes

Image in treeview Tkinter library in Python

python : tkinter treeview colors are not updating

Python Tkinter Treeview displaying mysql

For loop not working right

_tkinter.TclError: invalid command name ".!treeview"

Validate command not working in Tkinter

Button to clear Treeview table in Tkinter not working?

Tkinter treeview to display database results not working

Python for loop doesn't work right when it is inside of the command of a button

Continue working on the command line after finishing from tkinter GUI in python?

python tkinter tag_bind not working inside loop

TOC Heading not working if heading not clear

can i make the treeview of tkinter begins from the right side?

Command substitution in for loop not working

python tkinter - adding values from treeview column

TreeView does not output anything in a window Tkinter Python

Python - tkinter Treeview not updating integer variable

Python Tkinter Treeview search all entries