Book Image

Tkinter GUI Application Development HOTSHOT

By : Bhaskar Chaudhary
Book Image

Tkinter GUI Application Development HOTSHOT

By: Bhaskar Chaudhary

Overview of this book

<p>Tkinter is the built-in GUI package that comes with standard python distributions. This means it is easy to get started right away, without any extra installation or configuration. Tkinter’s strength lies in its simplicity of use and its intuitive nature which makes it suited for programmers and non-programmers alike. Once you get started, you will be surprised to see how a few lines of code can produce powerful GUI applications.</p> <p>Tkinter GUI Application Development Hotshot helps you learn the art of GUI programming—building real-world, productive and fun applications like text editor, drum machine, game of chess, media player, drawing application and many more. Each subsequent project builds on the skills acquired in the previous project. Also, learn to write multi-threaded and multi layered applications using Tkinter. Get to know modern best practices involved in writing GUI programs. Tkinter GUI Application Development Hotshot comes with a rich source of sample codes that you can use in your own projects in any discipline of your choice.</p> <p>Starting with a high level overview of Tkinter that covers the most important concepts involved in writing a GUI application, the book then takes you through a series of real world projects of increasing complexity, developing one project per chapter. After you have developed five full projects, the book provides you with some bare-bone skeleton codes for a few functional but incomplete projects, challenging you to put your skills to test by completing them.</p> <p>Finally, you are provided with tips for writing reusable, scalable, and quality GUI code for larger projects. The appendices provide a quick reference sheet for Tkinter.</p>
Table of Contents (16 chapters)
Tkinter GUI Application Development HOTSHOT
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

ttk widgets


The ttk widget is based on a revised and enhanced version of TIP #48 (http://tip.tcl.tk/48) specified style engine.

FILE: path\to\python27\\lib\lib-tk\ttk.py

The basic idea is to separate, to the extent possible, the code implementing a widget's behavior from the code implementing its appearance. Widget class bindings are primarily responsible for maintaining the widget state and invoking callbacks, and all aspects of the widgets appearance lies under themes.

You can substitute some Tkinter widgets with their corresponding ttk widgets (Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale, and Scrollbar).

However, Tkinter and ttk widgets are not completely compatible. The main difference is that Tkinter widget styling options like fg, bg, relief, and others are not supported options for ttk widgets. These styling options are instead moved to ttk.Style().

Here's a small Tkinter code sample:

Label(text="Who", fg="white", bg="black")
Label(text="Are You ?", fg="white", bg="black")

And here's its equivalent code in ttk:

style = ttk.Style()
style.configure("BW.TLabel", foreground="white", background="black")
ttk.Label(text="Who", style="BW.TLabel")
ttk.Label(text="Are You ?", style="BW.TLabel")

ttk also provides six new widget classes which are not available in Tkinter. These are Combob ox, Notebo ok, Progressb ar, Separator, Sizegrip, and Treevi ew.

ttk style names are as follows:

Widget class

Style name

Button

TButton

Checkbutto n

TCheckbutton

Combobox

TCombobox

Entry

TEntry

Frame

TFrame

Label

TLabel

LabelFrame

TLabelFrame

Menubutton

TMenubutton

Notebook

TNotebook

PanedWindow

TPanedwindow (note window is not capitalized!)

Progressbar

Horizontal.TProgressbar or Vertical.TProgressbar, based on the orient option.

Radiobutton

TRadiobutton

Scale

Horizontal.TScale or Vertical.TScale, based on the orient option.

Scrollbar

Horizontal.TScrollbar or Vertical.TScrollbar, based on the orient option.

Separator

TSeparator

Sizegrip

TSizegrip

Treeview

Treeview (note only single 'T' meaning notTTreview!)

Options available to all ttk widgets are as follows:

Option

Description

class

Specifies the window class. The class is used when querying the option database for the window's other options, to determine the default bindtags for the window, and to select the widget's default layout and style. This is a read-only option which may only be specified when the window is created.

cursor

specifies mouse cursor to be displayed for the widget

takefocus

Determines whether the window accepts the focus during keyboard traversal. 0, 1 or an empty string is returned. If 0, the window should be skipped entirely during keyboard traversal. If 1, the window should receive the input focus as long as it is viewable. An empty string means that the traversal scripts make the decision about whether or not to focus on the window.

style

May be used to specify a custom widget style.

Options accepted by all scrollable ttk widgets are as follows:

Option

Description

xscrollcommand

Used to communicate with horizontal scrollbars. When the view in the widget's window changes, the widget will generate a Tcl command based on the scrollcommand. Usually, this option consists of the Scrollbar.set() method of some scrollbar. This will cause the scrollbar to be updated whenever the view in the window changes.

yscrollcommand

Command for vertical scrollbars.

Methods from ttk.Widget class with their description are as follows:

Method

Description

identify(self, x, y)

Returns the name of the element at position x, y, or the empty string if the point does not lie within any element. x and y are pixel coordinates relative to the widget.

instate(self, statespec, callback=None, *args, **kw)

Test the widget's state. If callback is not specified, returns True if the widget state matches statespec and False otherwise. If callback is specified, then it will be invoked with *args, **kw if the widget state matches statespec. statespec is expected to be a sequence.

state(self, statespec=None)

Modify or inquire widget state. Widget state is returned if statespec is None, otherwise it is set according to the statespec flags, and then a new state spec is returned, indicating which flags were changed. statespec is expected to be a sequence.

We will not show all ttk widget specific options here. To obtain a list of available options for a ttk widget, use the help command.

To obtain help on any ttk widget/class, import ttk into the namespace using following command:

>>>import ttk

The following commands can then be used to get information on a particular widget:

Widget Name

Getting Help

Label

help(ttk.Label)

Button

help(ttk.Button)

CheckButton

help(ttk.Checkbutton)

Entry

help(ttk.Entry)

Frame

help(ttk.Frame)

LabelFrame

help(ttk.LabelFrame)

Menubutton

help(ttk.Menubutton)

OptionMenu

help(ttk.OptionMenu)

PanedWindow

help(ttk.PanedWindow)

RadioButton

help(ttk.Radiobutton)

Scale

help(ttk.Scale)

Scrollbar

help(ttk.Scrollbar)

Combobox

help(ttk.Combobox)

Notebook

help(ttk.Notebook)

Progressbar

help(ttk.Progressbar)

Separator

help(ttk.Separator)

Sizegrip

help(ttk.Sizegrip)

Treeview

help(ttk.Treeview)

The following given are some ttkVirtual events and situation when they are triggered:

Virtual Event

Triggered when

<<ComboboxSelected>>

The user selects an element from the list of values in the Combobox widget

<<NotebookTabChanged>>

A new tab is selected in the Notebook widget

<<TreeviewSelect>>

Selection changes in the Treeview widget.

<<TreeviewOpen>>

Just before settings the focus item to open = True.

<<TreeviewClose>>

Just after setting the focus item to open = False.

Each widget in ttk is assigned a style, which specifies the set of elements making up the widget and how they are arranged, along with dynamic and default settings for element options.

By default, the style name is the same as the widget's class name, but it may be overridden by the widget's style option. If the class name of a widget is unknown, use the method Misc.winfo_class() (somewidget.winfo_class()). Following given are few methods with their description of ttk styling:

Method

Description

configure(self, style, query_opt=None, **kw)

Query or sets the default value of the specified option(s) in style. Each key in kw is an option, and each value is either a string or a sequence identifying the value for that option.

element_create(self, elementname, etype, *args, **kw)

Create a new element in the current theme of given etype.

element_names(self)

Returns the list of elements defined in the current theme.

element_options(self, elementname)

Return the list of elementname options.

layout(self, style, layoutspec=None)

Define the widget layout for given style. If layoutspec is omitted, return the layout specification for given style.

layoutspec is expected to be a list or an object different than None that evaluates to False if you want to "turn off" that style. If it is a list (or tuple, or something else), each item should be a tuple, where the first item is the layout name, and the second item should have the format described below

A layout can be just None, if it takes no options, or a dictionary of options specifying how to arrange the element. The layout mechanism uses a simplified version of the pack geometry manager: given an initial cavity, each element is allocated a parcel.

Valid options: Values

Description

side: whichside

Specifies which side of the cavity to place the element; one of top, right, bottom or left. If omitted, the element occupies the entire cavity.

sticky: nswe

Specifies where the element is placed inside its allocated parcel.

children: [sublayout... ]

Specifies a list of elements to place inside the element. Each element is a tuple (or other sequence) where the first item is the layout name, and the other is a layout.

lookup(self, style, option, state=None, default=None)

Returns the value specified for option in style. If state is specified, it is expected to be a sequence of one or more states. If the default argument is set, it is used as a fallback value in case no specification for option is found.

map(self, style, query_opt=None, **kw)

Query or sets dynamic values of the specified option(s) in style. Each key in kw is an option, and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, or list, or something else of your preference. A statespec is compound of one or more states, and then a value.

theme_create(self, themename, parent=None, settings=None)

Creates a new theme. It is an error if themename already exists. If parent is specified, the new theme will inherit styles, elements and layouts from the specified parent theme. If settings are present, they are expected to have the same syntax used for theme_settings.

theme_names(self)

Returns a list of all known themes.

theme_settings(self, themename, settings)

Temporarily sets the current theme to themename, apply specified settings, and then restores the previous theme. Each key in settings is a style and each value may contain the keys configure, map, layout, and element create and they are expected to have the same format as specified by the methods configure, map, layout, and element_create respectively.

theme_use(self, themename=None)

If themename is None, returns the theme in use; otherwise, set the current theme to themename, refreshes all widgets and emits a <<ThemeChanged>> event.