2015-07-18 93 views
1

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

我想在不同的颜色之间在鼠标指针当前所在的项的背景。

回答

2

不,当它进入你无法跟踪/离开特定的行。但是,您可以跟踪它何时进入/离开小部件,并且可以使用列表框的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)) 
    ... 
2

下面是一个(半)试图通过结合<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