Python Tkinter : Listbox mouse enter event for a specific entry

标签 python tkinter listbox mouseover

可以使用 <Enter> 创建鼠标指针进入/离开整个列表框时的事件。/<Leave> .如何跟踪鼠标何时进入或离开列表框中的特定条目(行)?

我想用不同的颜色为鼠标指针当前所在条目的背景着色。

最佳答案

这是一个(半)尝试通过绑定(bind)到 <Motion> 来做你想做的事事件而不是对 <Enter><Leave> .这是因为 <Enter>仅当我们输入 Listbox 时才会引发从外面看,但是一旦我们进入 Listbox用鼠标,没有别的<Enter>将引发事件,我们无法跟踪鼠标位于哪个项目之上。

每次鼠标移动时都调用一个函数可能会导致工作过载,所以我认为这个功能不值得这样做(以这种方式)。

该程序仍然不能完美运行,我仍然必须了解原因:基本上,有时项目的背景和字体颜色没有正确更改,存在某种延迟或其他原因。

from tkinter import *


class CustomListBox(Listbox):

    def __init__(self, master=None, *args, **kwargs):
        Listbox.__init__(self, master, *args, **kwargs)

        self.bg = "white"
        self.fg = "black"
        self.h_bg = "#eee8aa"
        self.h_fg = "blue"

        self.current = -1  # current highlighted item

        self.fill()

        self.bind("<Motion>", self.on_motion)
        self.bind("<Leave>", self.on_leave)

    def fill(self, number=15):
        """Fills the listbox with some numbers"""
        for i in range(number):
            self.insert(END, i)
            self.itemconfig(i, {"bg": self.bg})
            self.itemconfig(i, {"fg": self.fg})

    def reset_colors(self):
        """Resets the colors of the items"""
        for item in self.get(0, END):
            self.itemconfig(item, {"bg": self.bg})
            self.itemconfig(item, {"fg": self.fg})

    def set_highlighted_item(self, index):
        """Set the item at index with the highlighted colors"""
        self.itemconfig(index, {"bg": self.h_bg})
        self.itemconfig(index, {"fg": self.h_fg})    

    def on_motion(self, event):
        """Calls everytime there's a motion of the mouse"""
        print(self.current)
        index = self.index("@%s,%s" % (event.x, event.y))
        if self.current != -1 and self.current != index:
            self.reset_colors()
            self.set_highlighted_item(index)
        elif self.current == -1:
            self.set_highlighted_item(index)
        self.current = index

    def on_leave(self, event):
        self.reset_colors()
        self.current = -1


if __name__ == "__main__":
    root = Tk()
    CustomListBox(root).pack()
    root.mainloop()

请注意,我使用了 from tkinter import *打字更快,但我建议您使用 import tkinter as tk .

关于Python Tkinter : Listbox mouse enter event for a specific entry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495881/

相关文章:

c# - ListBox.ItemsSource 的显示属性

c# - Listbox 所选项目内容到文本 block

python - 如何检查输入是否是Python中的自然数?

python - Canvas 的边框颜色 (tkinter)

python - Tkinter - 如何停止在 Canvas 窗口上方滚动

python-2.7 - Python 中的 Tix 教程

c# - 如何禁用 WPF ListBox 中的水平滚动?

python - Python中的元组树结构深度

python - Python 中的 mp4 元数据提取

python - Numpy 将一个数组的所有非零元素组合到另一个数组中