Using Menus in Tkinter


This is a quick post on how to use menu’s in Tkinter, if you are unfamiliar with Tkinter you might want to check out some of my other Tkinter related posts.

We are going to start of with a basic python Tkinter app:

#! /usr/bin/env python
from Tkinter import *

class App(Frame):

	def __init__(self, master):
		
		"""Initialise the base class"""
        	Frame.__init__(self,master)
        
        	"""Set the Window Title"""
        	self.master.title("TkInter Menus")
		self.configure(height=200,width=200)
        	"""Display the main window
        	with a little bit of padding"""
        	self.grid(padx=15, pady=15,sticky=N+S+E+W)

if __name__ == "__main__":
	root = Tk()
	app = App(root)
	root.mainloop()

Python Tkinter WindowWhat this gives us is basically a plain old blank Tkinter window, not too exciting. The next thing we are going to do is add create our root menu, before going any further you might want to read the excellent information about menu widgets in PythonWare’s Tkinter introduction. You don’t have to but it’s an excellent source of information.

To create the root menu we simply add the following command to our __init__ function:

#Create the Menu base
self.menu = Menu(self)
#Add the Menu
self.master.config(menu=self.menu)

No we are greeted with, well a blank window with a blank menu, the reason for this is because we haven’t added anything to it. What we are going to add to it is a menu, but not just any menu, a menu who’s parent is our menu base:

#Create our Python menu
self.tkMenu = Menu(self.menu)
#Add our Menu to the Base Menu
self.menu.add_cascade(label="TkMenu", menu=self.tkMenu)

Python Tkinter WindowNow we’re getting somewhere at least we have a menu now! The next step is to add items to our TkMenu:

#Add items to the menu
self.tkMenu.add_command(label="Simple", command=self.Simple)
self.tkMenu.add_separator()
self.tkMenu.add_command(label="Menu", command=self.Menu)

Python Tkinter MenuThat’s basically it! Adding the menu item’s is pretty simple, we specify it’s text and then tell it what function to call when the user clicks on the menu item. The two functions that I used don’t really do anything besides show a message box:

def Simple(self):
		tkMessageBox.showinfo("Simple", "Simple")
def Menu(self):
		tkMessageBox.showinfo("Menu", "Menu")

Well that’s it for this post, here is the code in its entirety:

#! /usr/bin/env python
from Tkinter import *

import tkMessageBox

class App(Frame):


	def __init__(self, master):
		
		"""Initialise the base class"""
        	Frame.__init__(self,master)
        
        	"""Set the Window Title"""
        	self.master.title("TkInter Menus")
		self.configure(height=200,width=200)
        	"""Display the main window
        	with a little bit of padding"""
        	self.grid(padx=15, pady=15,sticky=N+S+E+W)       
 
       		#Create the Menu base
        	self.menu = Menu(self)
        	#Add the Menu
        	self.master.config(menu=self.menu)
        	
		#Create our Python menu
		self.tkMenu = Menu(self.menu)
		#Add our Menu to the Base Menu
        	self.menu.add_cascade(label="TkMenu", menu=self.tkMenu)

		#Add items to the menu
		self.tkMenu.add_command(label="Simple", command=self.Simple)
		self.tkMenu.add_separator()
		self.tkMenu.add_command(label="Menu", command=self.Menu)
	
	def Simple(self):
		tkMessageBox.showinfo("Simple", "Simple")
	def Menu(self):
		tkMessageBox.showinfo("Menu", "Menu")        	


if __name__ == "__main__":
	root = Tk()
	app = App(root)
	root.mainloop()
selsine

del.icio.us del.icio.us

13 Responses to “Using Menus in Tkinter”

  1. learning python » Blog Archive » Using Menu’s in Tkinter
    Says:

    [...] This is a quick post on how to use menu’s in Tkinter, if you are unfamiliar with Tkinter you might want to check out some of my other Tkinter related posts. [...]

  2. learning python » Blog Archive » Creating a GUI using PyGTK and Glade
    Says:

    [...] After spending some time creating a GUI using TKinter and having it be pretty easy, but getting frustrated by how linked my code and the GUI was, I decided to look into creating a GUI using another toolkit. After looking around at the options for a while I settled on using PyGTK and Glade [...]

  3. learning python » Blog Archive » RSS reader - Part Four - Integrating with the GUI
    Says:

    [...] So far our RSS reader has been completely command-line, which is functional but not as nice as we’d really like to have it. So what we are going to do is integrate the GUI that I created in my two Tkinter GUI tutorials into our RSS application. [...]

  4. Joel
    Says:

    Having trouble with menus — specifically, I get a window, no menu. I’ve tried your example, pasting it in. Tried several others too. Same unsatisfactory result: A window, but no menu.

    I’m beginning to suspect that the current Python download is defective — how else to explain same result with at least 4 independent ‘text book examples’. I’d tell you what versions I’m using if I knew how to find it. (Learning my way around OSX and Unix at the same time. This is a Mac OSX10.4.7. The Python is ‘probably’ 2.4.

    A previous program, with buttons, still runs

    Thanks, JL

  5. selsine

    selsine
    Says:

    Hi Joel,

    If you want to test what version of python you have installed on your system simply run “python” from the Terminal to launch the interactive editor. You should get a message like this that shows your version:


    Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
    [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.

    (ctrl+d to quit)

    I’ve tested the code with version 2.4.2 and 2.5 and both work properly on my Mac. One thing to remember is that the menu’s will not show up on the window, they will appear in the “menu bar” along the top of the screen where menu’s appear on OS X.

    Take a look at the screenshot in the tutorial and I think you’ll see what I mean.

  6. Las Noyas de Taran
    Says:

    [...] Actualmente estoy siguiendo el tutorial en castellano sobre pyGTK que se puede encontrar en su pĂĄgina web. Necesito aprender a manejarme bien con esto para el proyecto, y es el paso en el que estoy ahora. Aunque podrĂ­a directamente ponerme con Glade o Gazpacho, que son dos diseĂąadores de interfaces grĂĄficas, prefiero primero aprender a crearlas con cĂłdigo a pelo, porque luego necesitarĂŠ manejarlas y asĂ­ adquiero soltura. AsĂ­ que mientras sigo el manual, que es un seĂąor libro, tambiĂŠn miro tutoriales sobre el manejo de Glade y como conectar las interfaces que se generan a nuestro cĂłdigo. QuizĂĄs la mejor pĂĄgina que he encontrado sobre el tema sea Learning Python con una serie de tutoriales en el idioma anglosajĂłn, asĂ­ que me he decidido a traducir (libremente, lo mejor que pueda xD) los que considere mĂĄs interesantes lo mejor que pueda, pues me obliga a fijarme bien lĂ­nea a lĂ­nea. El cĂłdigo lo dejarĂŠ tal cual, excepto los comentarios que los traducirĂŠ y que aĂąado la codificaciĂłn de caracteres para las tildes y la Ăą, y usarĂŠ sus capturas de pantalla, aunque por supuesto probarĂŠ antes cada ejemplo. AdemĂĄs traduzco el texto completo, por lo que algunas cosas obviamente no se refieren a mi, como comentarios sobre he usado esto o me he decidido por esto otro. AsĂ­ que ya os dejo con este primer artĂ­culo, titulado originalmente Creating a GUI using PyGTK and Glade, y escrito por Mark Mruss: DespuĂŠs de gastar algĂşn tiempo creando una GUI usando TKinter y habiendo sido bastante fĂĄcil, pero frustrĂĄndome por como se enlaza mi cĂłdigo y la GUI, decidĂ­ probar a crear una GUI usando otro toolkit. Tras echar un vistazo a las diferentes opciones durante un rato me decidĂ­ por usar PyGTK y [...]

  7. Matt
    Says:

    same problem as joel, on mac 10.4 using php 2.6.2 and the menu does not appear, copy and pasted several source code examples

  8. Ciprian Pop
    Says:

    It worked perfectly.
    Configuration:
    Linux version 2.6.31.5-desktop-1mnb (herton@n2.mandriva.com) (gcc version 4.4.1 (GCC) ) #1 SMP Fri Oct 23 01:46:54 EDT 2009

    One issue, though:
    the line

    self.tkMenu = Menu(self.menu)

    should be

    self.tkMenu = Menu(self.menu,tearoff=0)

  9. Ciprian Pop
    Says:

    Python 2.6.4, forgot to add.

  10. Ben
    Says:

    Hi. Just exploring tk under OSX. Put up a menu – File, help, etc, works with callback.

    First thing I ran into, though, was a “Python” menu leading the others; if I’m to code an application, I can’t have that. I googled the heck out of the web, nothing found that even remotely helps.

    Is there a way to get rid of the “Python” menu and put up a “My Application” menu?

    …you’d think this would be the first thing addressed in any menu demo…

  11. Ann-Lorrain
    Says:

    Ann-Lorrain

    learning python » Blog Archive » Using Menus in Tkinter

  12. cheap genuine diamond engagement rings
    Says:

    cheap genuine diamond engagement rings

    learning python » Blog Archive » Using Menus in Tkinter

  13. Alaine
    Says:

    Alaine

    learning python » Blog Archive » Using Menus in Tkinter

Leave a Reply

 

Popular Posts