Menu

The last widget we will look at is Menu.

The following code uses this to create the simple text editor shown in Figure 14.16, on the following page:

Download gui/menu.py

from Tkinter import * import tkFileDialog as dialog def save(root, text):

data = text.get('0.0', END) filename = dialog.asksaveasfilename( parent=root, filetypes=[('Text', '*.txt')], title= 'Save as...') writer = open(filename, 'w') writer.write(data) writer.close()

def quit(root): root.destroy()

menubar = Menu(window) filemenu = Menu(menubar)

filemenu.add_command(label='Save', command=lambda filemenu.add_command(label= 'Quit' , command=lambda menubar.add_cascade(label = 'File', menu=filemenu) window.config(menu=menubar)

window.mainloop()

The program begins by defining two functions: save, which saves the contents of a text widget, and quit, which closes the application. The save function uses tkFileDialog to create a standard "Save as..." dialog box, which will prompt the user for the name of a text file.

After creating and packing the Text widget, the program creates a menu-bar, which is the horizontal bar into which we can put one or more menus. it then creates a File menu and adds two menu items to it called Save and Quit. We then add the File menu to the menu bar and run mainloop.

Figure 14.16: A window with a menu

Was this article helpful?

0 0

Post a comment