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

丶灬走出姿态 提交于 2019-12-05 10:21:33

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 -command in config:

def foo():
    pass

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!