如何获取所选树视图项的值? [英] How to get the value of a selected treeview item?
问题描述
我已经查看了几篇关于此的帖子,他们已经完成了以下操作
I've looked at several posts regarding this and they've done the following
-我得到的输出是空白的
-The output i get is blank
-我得到的输出是 id,除非有人可以告诉我如何操作它,否则这实际上是无用的
-The output i get is the id, which is practically useless unless somebody can show me how to manipulate it
-根本没有输出
我只想能够在树视图中单击一个项目,并立即获得我刚刚单击的文本
i just want to be able to click an item in treeview, and instantly be given the text i just clicked
def OnDoubleClick(event):
item = course1_assessments.focus()
print (item)
course1_assessments.bind("<<TreeviewSelect>>", OnDoubleClick)
如果我点击第一个项目,这个代码给我'I001',当我点击第二个项目时给我'I002';id 假设这些是树中的列值,但对我来说仍然没用
This code gives me 'I001' if i click the first item, and 'I002' when i click the second; id assume these are column values in the tree, but still useless to me
推荐答案
您可以使用小部件的 selection
方法获取所选项目的列表.它将返回一个项目 ID 列表.您可以使用 item
方法获取有关每个项目的信息.
You can get a list of the selected items with the selection
method of the widget. It will return a list of item ids. You can use the item
method to get information about each item.
例如:
import tkinter as tk
from tkinter import ttk
class App:
def __init__(self):
self.root = tk.Tk()
self.tree = ttk.Treeview()
self.tree.pack(side="top", fill="both")
self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)
for i in range(10):
self.tree.insert("", "end", text="Item %s" % i)
self.root.mainloop()
def on_tree_select(self, event):
print("selected items:")
for item in self.tree.selection():
item_text = self.tree.item(item,"text")
print(item_text)
if __name__ == "__main__":
app = App()
这篇关于如何获取所选树视图项的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!