【问题标题】:Storing Class Instances in a Python Tkinter Treeview在 Python Tkinter 树视图中存储类实例
【发布时间】:2017-10-22 17:32:03
【问题描述】:

我的 tkinter GUI 中有一个树视图。每次我创建另一个类的新实例时,都会在树视图中插入一个新项目。如何将类实例存储在树视图中,以便在树视图中单击实例时调用实例上的函数?

【问题讨论】:

  • 您需要存储从树视图到类的引用,然后生成一个包含类可用功能的上下文菜单。除非您有某些在选择时启用/禁用的按钮。
  • 从树视图中引用是什么意思?
  • 像字典一样存储引用。使索引与树条目的文本相同。然后将事件绑定到树。

标签: python tkinter treeview ttk


【解决方案1】:
class MyClass(object):
    def __init__(self, text):
        self.text = text
        self.value = len(text) * 5


class App(object):
    def __init__(self):
        self.root = Tk()
        self.tree = ttk.Treeview(self.root)
        self.construct()

    def construct(self):
        self.tree["columns"]=("one","two")
        self.tree.column("one", width=100 )
        self.tree.column("two", width=100)
        self.tree.heading("one", text="coulmn A")
        self.tree.heading("two", text="column B")

        self.tree.insert("" , 0,    text="Line 1", values=("1A","1b"))

        id2 = self.tree.insert("", 1, "dir2", text="Dir 2")
        self.tree.insert(id2, "end", "dir 2", text="sub dir 2", values=("2A","2B"))

        self.tree.insert("", 3, "dir3", text="Dir 3")
        self.tree.insert("dir3", 3, text="sub dir 3",values=("3A"," 3B"))
        self.tree.bind("<Double-1>", self.on_double_click)

        self.tree.pack()

        self.my_dict = {
            'Dir 2' : MyClass('Dir 2'),
            'Dir 3': MyClass('Dir 3'),
            'sub dir 2': MyClass('sub dir 2'),
            'sub dir 3': MyClass('sub dir 3')
            }

        self.root.mainloop()

    def on_double_click(self, event):
        item = self.tree.selection()[0]
        print(self.my_dict[self.tree.item(item,"text")])
        print(self.my_dict[self.tree.item(item,"text")].value)

if __name__ == '__main__':
    App()

self.my_dict 存储对您尝试调用的对象的直接引用。当您双击一个对象时,将执行on_double_click 事件,在这种情况下,它会打印对象引用和在__init__ 上实例化的对象的.value 属性。

这是你可以准确地写出你想要做的事情的基础。

【讨论】:

  • 当您添加一个新对象时,请务必使用正确的键将其添加到dict
  • 谢谢!但是如何获得应该用作键的值?
猜你喜欢
  • 1970-01-01
  • 2011-11-21
  • 2020-10-22
  • 1970-01-01
  • 2019-02-03
  • 2020-10-19
  • 2016-03-16
  • 2021-01-28
  • 1970-01-01
相关资源
最近更新 更多