The tkinter GUI Module and Tools

tkinter (named Tkinter in Python 2.X, and a module package in Python 3.0) is a portable graphical user interface (GUI) construction library shipped with Python as a standard library module. tkinter provides an object-based interface to the open source Tk library and implements native look and feel for Python-coded GUIs on Windows, X-Windows, and Mac OS. It is portable, simple to use, well documented, widely used, mature, and well supported. Other portable GUI options for Python such as wxPython and PyQT are third-party extensions with richer widget sets but generally more complex coding requirements.

tkinter Example

In tkinter scripts, widgets are customizable classes (e.g., Button, Frame), options are keyword arguments (e.g., text="press"), and composition refers to object embedding, not pathnames (e.g., Label(top,...)):

from tkinter import *               # widgets, constants

def msg():                          # callback handler
    print('hello stdout...')

top = Frame()                       # make a container
top.pack()
Label(top,  text="Hello world").pack(side=TOP)
widget = Button(top, text="press", command=msg)
widget.pack(side=BOTTOM)
top.mainloop()

tkinter Core Widgets

Table 1-21 lists the primary widget classes in the tkinter module. These are true Python classes that can be subclassed and embedded in other objects. To create a screen device, make an instance of the corresponding class, configure it, and arrange it with one of the geometry manager interface methods (e.g., Button(text='hello').pack()). In addition to Table 1-21’s classes, the tkinter module provides a large set of predefined names (a.k.a. constants) used to configure widgets (e.g., RIGHT, BOTH, YES); these are automatically loaded from tkinter.constants (Tkconstants in Python 2.X).

Table 1-21. Module tkinter core widget classes

Widget class

Description

Label

Simple message area

Button

Simple labeled pushbutton widget

Frame

Container for attaching and arranging other widget objects

Toplevel, Tk

Top-level windows managed by the window manager

Message

Multiline text-display field (label)

Entry

Simple single-line text entry field

Checkbutton

Two-state button widget, used for multiple-choice selections

Radiobutton

Two-state button widget, used for single-choice selections

Scale

A slider widget with scalable positions

PhotoImage

Image object for placing full-color images on other widgets

BitmapImage

Image object for placing bitmap images on other widgets

Menu

Options associated with a Menubutton or top-level window

Menubutton

Button that opens a Menu of selectable options/submenus

Scrollbar

Bar for scrolling other widgets (e.g., Listbox, Canvas, Text)

Listbox

List of selection names

Text

Multiline text browse/edit widget, support for fonts, etc.

Canvas

Graphics drawing area: lines, circles, photos, text, etc.

OptionMenu

Composite: pull-down selection list

PanedWindow

A multipane window interface

LabelFrame

A labeled frame widget

Spinbox

A multiple selection widget

ScrolledText

Python 2.X name (available in module tkinter.scrolledtext in Python 3.0); Composite: text with attached scrollbar

Dialog

Python 2.X name (available in module tkinter.dialog in Python 3.0); Old: common dialog maker (see newer common dialog calls in the next section)

Common Dialog Calls

Module tkinter.messagebox (tkMessageBox in Python 2.X)

showinfo(title=None, message=None, **options)
showwarning(title=None, message=None, **options)
showerror(title=None, message=None, **options)
askquestion(title=None, message=None, **options)
askokcancel(title=None, message=None, **options)
askyesno(title=None, message=None, **options)
askretrycancel(title=None, message=None, **options)

Module tkinter.simpledialog (tkSimpleDialog in Python 2.X)

askinteger(title, prompt, **kw)
askfloat(title, prompt, **kw)
askstring(title, prompt, **kw)

Module tkinter.colorchooser (tkColorChooser in Python 2.X)

askcolor(color = None, **options)

Module tkinter.filedialog (tkFileDialog in Python 2.X)

class Open
class SaveAs
class Directory
askopenfilename(**options)
asksaveasfilename(**options)
askopenfile(mode="r", **options)
asksaveasfile(mode="w", **options)
askdirectory(**options)

The common dialog call options are defaultextension (added to filename if not explicitly given), filetypes (sequence of (label, pattern) tuples), initialdir (initial directory, remembered by classes), initialfile (initial file), parent (window in which to place the dialog box), and title (dialog box title).

Additional tkinter Classes and Tools

Table 1-22 lists some commonly used tkinter interfaces and tools beyond the core widget class and standard dialog set.

Table 1-22. Additional tkinter tools

Tool category

Available tools

tkinter linked-variable classes

StringVar, IntVar, DoubleVar, BooleanVar (in tkinter module)

Geometry management methods

pack, grid, place widget object methods, plus configuration options in module

Scheduled callbacks

Widget after, wait, and update methods; file I/O callbacks

Other tkinter tools

Clipboard access; bind/Event low-level event processing widget object methods; widget config options; modal dialog box support

tkinter extensions (search the Web)

PMW: more widgets; PIL: images; tree widgets, font support, drag-and-drop, tix widgets, ttk themed widgets, etc.

Tcl/Tk-to-Python/tkinter Mappings

Table 1-23 compares Python’s tkinter API to the base Tk library as exposed by the Tcl language. In general, Tcl’s command strings map to objects in the Python language. Specifically, in Python’s tkinter, the Tk GUI interface differs from Tcl in the following ways:

Creation

Widgets are created as class instance objects by calling a widget class.

Masters (parents)

Parents are previously created objects, passed to widget class constructors.

Widget options

Options are constructor or config keyword arguments, or indexed keys.

Operations

Widget operations (actions) become tkinter widget class object methods.

Callbacks

Callback handlers are any callable object: function, method, lambda, class with __call__ method, etc.

Extension

Widgets are extended using Python class inheritance mechanisms.

Composition

Interfaces are constructed by attaching objects, not by concatenating names.

Linked variables

Variables associated with widgets are tkinter class objects with methods.

Table 1-23. Tk-to-tkinter mappings

Operation

Tcl/Tk

Python/tkinter

Creation

frame .panel

panel = Frame()

Masters

button .panel.quit

quit = Button(panel)

Options

button .panel.go -fg black

go = Button(panel, fg='black')

Configure

.panel.go config -bg red

go.config(bg='red') go['bg'] = 'red'

Actions

.popup invoke

popup.invoke()

Packing

pack .panel -side left -fill x

panel.pack(side=LEFT, fill=X)

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

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