Search code examples
pythonbindingtkintertreeviewheading

How to bind an action to the heading of a tkinter treeview in python?


I am using the tkinter Treeview widget to show a database. The command when clicking on one of the headings is used for sorting the table based on the clicked column.

Additionally I want a tooltip box show up as soon as I hover (or right click) over one of the headings. The tooltips aren't a problem for other widgets but the heading of a treeview isn't a full widget of course.

How can I bind any action to the headings except for the usual command?


Solution

  • 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":
            ...