How to associate action with tkinter tree title in python?

I am using the tkinter widget Treeviewto display the database. The command when you click on one of the headers is used to sort the table based on the click of a column.

In addition, I want the tooltip to appear as soon as I hover (or right-click) one of the headers. Tooltips are not a problem for other widgets, but the title of the tree structure is certainly not a complete widget.

How to associate any action with headers, with the exception of the usual command?

+4
source share
3 answers

You can associate events with treeview widgets. The widget has a method called identify , which can be used to determine which part of the event tree has occurred.

For instance:

...
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":
        ...
+4
source

use -command in config:

def foo():
    pass

tree.heading(column1, text = 'some text', command = foo)
+2
source

Use the command tree.headingas suggested by Mihail above, but note that if you work from class, you will need to pass yourself into the method as soon as possible.

Here is a Python 2 snippet that loads a tree view and demonstrates a call to both a method and an external function:

import Tkinter
import ttk

class 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()

Please note that for some reason, the first click does not seem to work right away, but gets stuck in the buffer until you click a second time - I really want to hear anyone who explains this.

0
source

Source: https://habr.com/ru/post/1599271/


All Articles