How to bind an action to the heading of a tkinter treeview in python?
You can bind the events to the treeview widget itself. The widget has a method named identify which can be used to determine which part of the treeview the event occurred over.
For example:
...self.tree = ttk.Treeview(...)self.tree.bind("<Double-1>", self.on_double_click)...def on_double_click(self, event): region = self.tree.identify("region", event.x, event.y) if region == "heading": ...
Use the tree.heading
command as proposed by Mihail above, but note that if you are running from within a class
, you'll need to pass a self into the method as usual.
Here is a Python 2 snippet that will load a treeview and demonstrate calling both a method and an external function:
import Tkinterimport ttkclass TreeWindow: def __init__(self): win = Tkinter.Tk() tree = ttk.Treeview(win,height=10,padding=3) self.tree = tree self.win = win self.tree["columns"] = ("Column 1","Column 2") self.tree.grid(row=1,column=0,sticky=Tkinter.NSEW) self.tree.column("Column 1", width=100) self.tree.heading("Column 1", text="Column 1", command=PrintColumnName1) self.tree.column("Column 2", width=100) self.tree.heading("Column 2", text="Column 2", command=self.PrintColumnName2) self.tree.insert('', 0, text="Row 1", values=("a",1)) self.tree.insert('', 1, text="Row 2", values=("b",2)) self.win.mainloop() def PrintColumnName2(self): print("Column 2")def PrintColumnName1(): print("Column 1")treeWindow = TreeWindow()
Note for some reason, the first click doesn't seem to work immediately but gets stuck in the buffer until you click a second time - very eager to hear anyone with an explanation for this.