2

I'm trying to show a context menu when an item in a Listbox widget is right clicked. The problem is that if a bind to the listbox, the whole Listbox will be active for send the event and it doesn't seem possible to bind to the list items only. I can't use <<ListboxSelect>> because it will be trigged on left click. So I tried to use the methods curselection() but I fell into unwanted results (the right clicked item doesn't have to be selected). I think I need to simulate <<ListboxSelect>> using generate_event() and nearest(). Can someone tell me how to do that or maybe where can i found the defaults binding inside tkinter package ?

4

1 回答 1

2

您将需要使用nearest(event.y). 调用回调时绑定到右键弹出菜单。

import Tkinter

def context_menu(event, menu):
    widget = event.widget
    index = widget.nearest(event.y)
    _, yoffset, _, height = widget.bbox(index)
    if event.y > height + yoffset + 5: # XXX 5 is a niceness factor :)
        # Outside of widget.
        return
    item = widget.get(index)
    print "Do something with", index, item
    menu.post(event.x_root, event.y_root)

root = Tkinter.Tk()
aqua = root.tk.call('tk', 'windowingsystem') == 'aqua'

menu = Tkinter.Menu()
menu.add_command(label=u'hi')

listbox = Tkinter.Listbox()
listbox.insert(0, *range(1, 10, 2))
listbox.bind('<2>' if aqua else '<3>', lambda e: context_menu(e, menu))
listbox.pack()
root.mainloop()
于 2013-02-13T21:45:38.120 回答