Adding the contextual menu

In this quick iteration, we add a contextual pop-up menu or the right-click menu with shortcuts to some common operations on the player.

For now, we will add just two functions to the right-click menu: Play and Delete.

After completion, the right-click menu will open, as shown in the following screenshot:

Adding the contextual menu

Engage Thrusters

Step 1 – creating the contextual menu

We have done similar contextual menus in our text editor, so we do a quick round up.

We add a new method, context_menu, and call it from the GUI __init__ method, as follows (see Code 5.06 main-gui.py):

def create_context_menu(self):
   self.context_menu = Menu(self.root, tearoff=0)
   self.context_menu.add_command(label="Play", command=self.identify_track_to_play)
   self.context_menu.add_command(label="Delete", command=self.del_selected)

We also define a show_context_menu method and bind it to right-click of mouse<<Button-3>> from within our create_list_frame, immediately next to where the Listbox widget is defined, as follows:

def show_context_menuContext_menu(self,event):
   self.context_menu.tk_popup(event.x_root+45, event.y_root+10,0)

Step 2: overriding the close button

While we are at it, let us code a little overlooked function. Now that we have the capability to loop over entire playlists, we do not want the player to close without stopping the songs being played. Let us, therefore, override the root.destroy() method to stop tracks before exiting.

To override the destroy method, we first add a protocol override method to our GUI __init__ method, as follows (see Code 5.06 main-gui.py):

self.root.protocol('WM_DELETE_WINDOW', self.close_player)

Finally let's define our close_player method, as follows:

def close_player(self):
   if tkMessageBox.askokcancel("Quit", "Really want to quit?"):
     try:
        self.player.pause()
     except:
        pass
     self.root.destroy()

Objective Complete – Mini Debriefing

The contextual menu is now added to our program. A user can now right-click on an item and select to play or delete it.

We have also overridden our close button to ensure that any playing track is stopped before we exit the player.

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

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