Hi

I am trying to get a tkinter UI to allow me to do two things.

  • When I right click in a Treeview widget and my mouse pointer is over an item I would like the item to be selected as if the user clicked on it
  • When I right click on the blank space in the Treeview I would like to clear the current selection.

How do you determine which item your mouse cursor is over on a widget in tkinter.

Thanks for the help in advance.

From widget method of the event parameter.

You would bind <Button-3> to the item Click Here. For whitespace, you would have to test event.x and event.y to see if you are over white space or not. This uses a left click to determine the location (event.x, event.y) to draw the snowman, but the principle is the same. For anything more detailed, you will have to post your code. Anyone who has been in any forum for even a short time knows that guessing what the OP is trying to do is a complete waste of time.

from Tkinter import *

class Snowman:
    def __init__(self, root):
        self.cv = Canvas( root, width=300, height=300 )
        self.cv.create_text( 150, 20, text="Left-Click anywhere", \
                             font="Arial" )
        self.draw_snowman(150, 150)

        self.cv.bind( "<Button-1>", self.change_coord )
        self.cv.pack()

    def change_coord(self, event):
        self.cv.delete( self.head, self.body, self.arm1, self.arm2 )
        self.draw_snowman(event.x, event.y)

    def draw_snowman(self, x, y):
        self.head = self.cv.create_oval( x-10, y-10, x+10, y+10, fill="white" )
        self.body = self.cv.create_oval( x-15, y+10, x+15, y+40, fill="white" )
        self.arm1 = self.cv.create_oval( x-20, y+15, x-10, y+30, fill="white" )
        self.arm2 = self.cv.create_oval( x+20, y+15, x+10, y+30, fill="white" )

top = Tk()
Snowman(top)
mainloop()

Thank you very much for the quick response.

I was merely inquiring as to the best way to get the current item (in a tkinter Treeview widget) when a user right clicks on an item. By default the widget does not select the item on a button-3 click only on a button-1 click.

It does not seem that the event carries this information.

The idea is to perform the selection of the item, the same way a button-1 click would, by using button-3 and then popup a context menu. I can create the context menu withou any problem but the rest eludes me. I will post code if I have something that is anywhere close to working.

I have managed to get it to work. In order to get the item that the mouse is over when the right click (Button-3) ocurred you pass the x and y coordinates to the Treeview.identify method and specify that you want the item to be returned. E.g

ttk.Treeview.identify('item', e.x, e.y)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.