In this third part of the tutorial I will deter from the usual path of taking on every standard widget and show you how to create a window with a popup menu using tkinter.ttk.
Difficulty: moderately easy (3/10)
Example: A window with popup menu
This example details how to create a root window class with a popup. The result will look like this:
Code for the example (gist):
1 from tkinter import *Explanation of the code:
2 from tkinter.ttk import *
4 class root_window_with_popup(Tk):
5 def __init__(self):
10 self.label = Label(self, text='Right click to show popup')
11 self.label.pack(anchor = N, fill=NONE, expand=YES, pady = 40)
13 self.popup = Menu(self, tearoff=0)
14 self.popup.add_command(label="Quit", command=self.destroy)
16 self.bind("<button-3>", self.do_popup)
20 def do_popup(self, event):
21 self.popup.tk_popup(event.x_root, event.y_root, 0)
23 if __name__ == '__main__':
So what does the root window class do?
- (6-8) Call parent constructor, set size settings, set title.
- (10-11) Add a helpful label to the window that instructs what to do.
- (13-14) Create the menu, like in the previous example. It just is not nested here.
- (16) Call the do_popup callback method on the press of the third mouse button. Note: this is the first place I show the bind method. It is used to connect events with actions/methods, much like the command keyword for the menu entries.
- (21): Display the popup window at the position of the mouse (which is passed as event).
- tkinter.Menu.tk_popup(x, y, entry='')
- x, y: root coordinates of where to display the popup menu
- entry: index of the entry which is selected