A floating menu

In order to place a Menu at a specific location we can use the place method. The place method takes two arguments: x and y. As the names imply these are coordinates of the exact location at which to draw the menu.

Since we will be binding this menu's creation to the right-click of a mouse, we will have access to an event object inside the bound function. It may seem intuitive, therefore, to just pass the x and y attributes of the event object to the place method and assume this will put the menu where the mouse was clicked.

The problem with this, however, is that the event object's coordinates are relative to the widget that  was bound, whereas the place system is relative to the user's screen. This means if the user is not running our application full-screen, the menu could be drawn somewhere completely outside the application!

In order to solve this problem we can use the winfo_x and winfo_y methods on the main window (our Tk widget). These will get the coordinates of our window relative to the user's screen, which we can then add to the x and y attributes of our event to get the location of the click.

To see all of this in action, open up your menu.py file and add in the following code between window.configure(menu=menu) and lab.pack(padx=50, pady=50):

context_menu = tk.Menu(win)
context_menu.add_command(label='close', command=win.destroy)

def on_right_click(event):
x = win.winfo_x() + event.x
y = win.winfo_y() + event.y

context_menu.post(x, y)

win.bind('<Button-3>', on_right_click)

Once again we need a Menu widget to act as our right-click menu. We add a command called close, which calls the destroy method on our main window, exiting our application.

A function is defined that will be bound to the right-click event, which is <Button-3>.

This function does what was described previously in order to calculate the x and y positions at which we want to place our menu. We then call post with these coordinates to spawn our context menu.

Run this final version of our demo application and try right-clicking somewhere inside the window. You should see a menu come up with a close option. Click this to close the application again:

With knowledge of Tkinter's Menu widget fresh in our minds let's grab our text editor application and add in some menus.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset