如何从ttk.Treeview小部件中清除项目?

2024-09-29 11:16:06 发布

您现在位置:Python中文网/ 问答频道 /正文

ing_scroll = Scrollbar(window1_frame1, orient=VERTICAL)
ingredients = ttk.Treeview(window1_frame1, yscrollcommand=ing_scroll.set, height=5, columns=['Ingredient', 'Amount'], show="headings")
ingredients.heading("Ingredient", text='Ingredient')
ingredients.column("Ingredient", width=7)
ingredients.heading("Amount", text='Amount')
ingredients.column("Amount", width=1)
ing_scroll.config(command=ingredients.yview)
ing_scroll.pack(side=RIGHT, fill=Y)
ingredients.pack(side=LEFT, fill='both', expand=1)

def OnRecpSelect(event):
    DB = menu_combo.get()
    mytable = recipe_combo.get()
    ingredient_list = TKengine.pull_ingredients(DB, mytable)
    # NEED TO CLEAR THE INGREDIENTS TTK:TREEVIEW OBJECT HERE!
    for i in ingredient_list: 
        ingre = i[1]
        amoun = i[2]
        value = ingre,amoun
        ingredients.insert('',0,values=value)

配料表是一个显示如下内容的列表。。。(“糖”,“一杯”)等等。。。def用于选中的组合框,所以我希望treeview能够清除,而不仅仅是继续添加更多的成分。不幸的是,我没有看到clear()方法。

如果有一种程序化的方法来识别首先出现的是什么(枚举一个行数会很好…),这会让我发疯。我在文档中确实注意到您可以使用delete方法,但它想知道要删除的项是什么。。。如果我使用:

ingredients.delete('',0)

我明白了

TclError: Item 0 not found

所以我想它想要一些像“糖”一样的东西。。。

当然,这是一个陷阱22,因为如果你选择组合框并想清除配料树视图,同一配料项目并不在每个配方中,那么我们如何知道要删除哪些项目?。。。

如果你需要更多的细节请告诉我。。。我对使用treeview对象还不太熟悉,但它让我只想在画布上使用两个列表框。


Tags: 方法textcolumnwidthfillamountsidepack
2条回答

当您在树上插入一个项时,insert方法返回一个项id。这就是您给delete方法的内容。

另外,给定一个项id(例如根项),您可以使用get_children方法获得其所有子项的列表。如果不给get_children提供任何参数,它将返回属于根元素的所有项的列表。然后可以遍历此列表以删除项。

这些都记录在docs.python.orgtreeview docs中。

为了使代码更简洁和更具python风格:

map(ingredients.delete, ingredients.get_children())

相关问题 更多 >