Search code examples
pythontkintertreeview

tkinter - Bind a different <Enter> event to each row in Treeview widget


I want to create a unique, small tooltip window to appear when I hover over each row of a Treeview widget.

I can't work out how to bind <Enter> and <Leave> events to each row uniquely.


Solution

  • No need to <Enter> or <Leave>. You can use <Motion> instead: This code is a modified version of this post

    import tkinter as tk
    from tkinter import Label, ttk
    
    
    def highlight_row(event):
        tree = event.widget
        item = tree.identify_row(event.y)
        if tree.item(item,'text')!='':
            lbl.config(text=tree.item(item,'text'))
            lbl.place(x=event.x, y=event.y)
        else:
            lbl.place_forget()
        tree.tk.call(tree, "tag", "remove", "highlight")
        tree.tk.call(tree, "tag", "add", "highlight", item)
    
    root = tk.Tk()
    
    tree = ttk.Treeview(root, style = 'W.TButton')
    vsb = ttk.Scrollbar(root, command=tree.yview)
    tree.configure(yscrollcommand=vsb.set)
    
    vsb.pack(side="right", fill="y")
    tree.pack(side="left", fill="both", expand=True)
    
    tree.tag_configure('highlight', background='lightblue')
    tree.bind("<Motion>", highlight_row)
    lbl=Label(root,bg="white")
    for i in range(100):
        tree.insert("", "end", text=f"Item #{i+1}")
        tree.tag_bind(i, '<Motion>', highlight_row)
    
    root.mainloop()