I have a treeview in my tkinter GUI. Everytime I create a new instance of my other class, a new item is inserted into the treeview. How could I store the class instance in the treeview so that I can call a function on the instance when I click on it in the treeview?
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()
The self.my_dict
stores a direct reference to the objects you are trying to call. When you double-click on an object, the on_double_click
event is executed, where in this case, it prints the object reference and the object's .value
attribute that gets instantiated on __init__
.
This is the basis by which you can write what you're trying to do exactly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.