top of page

Python Tkinter

Public·1 member

Tkinter Tutorial 5: Application Windows

Creating Base Window

There’s only one window on the screen; the root window. This is automatically created when you call the Tk constructor:


Syntax:

from Tkinter import *

root = Tk()

# create window contents as children to root...

root.mainloop()

If you need to create additional windows, you can use the Toplevel widget.


Example:

from Tkinter import *

root = Tk()

# create root window contents...

top = Toplevel()

# create top window contents...

root.mainloop()


Creating menus

To create a menu, you create an instance of the Menu class, and use add methods to add entries to it:

  • add_command(label=string, command=callback) adds an ordinary menu entry.

  • add_separator() adds an separator line. This is used to group menu entries.

  • add_cascade(label=string, menu=menu instance) adds a submenu (another Menu instance). This is either a pull-down menu or a fold-out menu, depending on the parent.


Example:

Creating a small menu

from Tkinter import *

def callback():
    print "called the callback!"

root = Tk()

# create a menu
menu = Menu(root)
root.config(menu=menu)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=callback)
filemenu.add_command(label="Open...", command=callback)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=callback)

helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=callback)

mainloop()


Toolbars

In the following example, we use a Frame widget as the toolbar, and pack a number of ordinary buttons into it.


from Tkinter import *

root = Tk()

def callback():
    print "called the callback!"# create a toolbar
toolbar = Frame(root)

b = Button(toolbar, text="new", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)

b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)

toolbar.pack(side=TOP, fill=X)

mainloop()


Status Bars

Implementing a status bar with Tkinter is trivial: you can simply use a suitably configured Label widget, and reconfigure the text option now and then. Here’s one way to do it:


status = Label(master, text="", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill=X)

Example of status bar:

class StatusBar(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.label = Label(self, bd=1, relief=SUNKEN, anchor=W)
        self.label.pack(fill=X)

    def set(self, format, *args):
        self.label.config(text=format % args)
        self.label.update_idletasks()

    def clear(self):
        self.label.config(text="")
        self.label.update_idletasks()

In next tutorial we will learn about dialog box.


7 Views
bottom of page