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()
What 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)
Now 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)
That’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()




March 27th, 2006 at 11:00 pm
[...] 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. [...]
May 7th, 2006 at 9:48 pm
[...] 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 [...]
July 9th, 2006 at 8:54 pm
[...] 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. [...]
October 8th, 2006 at 8:50 am
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

selsine Says:October 10th, 2006 at 8:40 am
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.
April 7th, 2007 at 3:24 pm
[...] 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 [...]