鼠标悬停时如何更改行颜色?Tkinter 树视图 [英] How to change row color when mouse over? Tkinter Treeview

查看:41
本文介绍了鼠标悬停时如何更改行颜色?Tkinter 树视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在使用 Tkinter ttk.Treeview 小部件,我已经能够使用 ttk.Style 更改很多小部件的样式,但遗憾的是我找不到解决方案这个问题:

I have been working with the Tkinter ttk.Treeview widget lately and I have been able to change a lot the widget's style using a ttk.Style, but sadly I am unable to find a solution to this problem:

如何在光标/鼠标结束时更改项目的颜色?

How can I change the item's colour when the cursor/mouse is over?

就像Tkinter.Buttonactivebackground 选项.与 VS CODE 树状视图类似:当您在浏览器中导航时,光标下的文件/文件夹会更改背景颜色.

Like the activebackground option of Tkinter.Button. Like the VS CODE treeview: When you are navigating the explorer, the file/ folder under the cursor changes the background colour.

推荐答案

可以通过标签来控制一行的颜色,所以解决方案的第一部分就是定义一个标签来高亮一行:

You can control the color of a row with a tag, so the first part of the solution is to define a tag to highlight a row:

tree.tag_configure('highlight', background='lightblue')

接下来,编写一个方法,从树中的所有项目中删除该标签,然后为光标下的项目添加该标签.底层 tk 小部件具有添加和删除标签的方法,但这些方法并未公开,因此我们需要直接调用底层 tk 代码.

Next, write a method that will remove that tag from all items in the tree and then add it for the item under the cursor. The underlying tk widget has methods for adding and removing tags but those methods aren't exposed, so we'll need to directly call the underlying tk code.

def highlight_row(event):
    tree = event.widget
    item = tree.identify_row(event.y)
    tree.tk.call(tree, "tag", "remove", "highlight")
    tree.tk.call(tree, "tag", "add", "highlight", item)

最后,将函数绑定到事件:

Finally, bind the function to the <Motion> event:

tree.bind("<Motion>", highlight_row)


这是一个完整的工作示例:


Here is a complete working example:

import tkinter as tk
from tkinter import ttk


def highlight_row(event):
    tree = event.widget
    item = tree.identify_row(event.y)
    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)


for i in range(100):
    tree.insert("", "end", text=f"Item #{i+1}")
    tree.tag_bind(i, '<Motion>', highlight_row)

root.mainloop()

这篇关于鼠标悬停时如何更改行颜色?Tkinter 树视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆