【问题标题】:Python Tkinter treeview.heading command not working right in for loopPython Tkinter treeview.heading 命令在 for 循环中无法正常工作
【发布时间】:2020-07-09 16:19:08
【问题描述】:

我正在尝试为 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()

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

【问题讨论】:

    标签: python-3.x tkinter treeview


    【解决方案1】:

    如果我改变了

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

    好像解决了问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多