它可以創建當鼠標指針進入/離開使用<Enter>
/<Leave>
整個列表框事件進入事件。如何跟蹤鼠標進入或離開列表框中的特定條目(行)?Python的Tkinter的:列表框鼠標的特定條目
我想在不同的顏色之間在鼠標指針當前所在的項的背景。
它可以創建當鼠標指針進入/離開使用<Enter>
/<Leave>
整個列表框事件進入事件。如何跟蹤鼠標進入或離開列表框中的特定條目(行)?Python的Tkinter的:列表框鼠標的特定條目
我想在不同的顏色之間在鼠標指針當前所在的項的背景。
不,當它進入你無法跟蹤/離開特定的行。但是,您可以跟蹤它何時進入/離開小部件,並且可以使用列表框的index
方法計算鼠標結束的項目。如果您給出「@ x,y」形式的索引,它將返回數字索引。
例如:
self.listbox.bind("<Enter>", self.on_enter)
...
def on_enter(self, event):
index = self.listbox.index("@%s,%s" % (event.x, event.y))
...
下面是一個(半)試圖通過結合<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
。