Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Tkinter GUI Application Development Blueprints

You're reading from   Tkinter GUI Application Development Blueprints Master GUI programming in Tkinter as you design, implement, and deliver 10 real-world applications

Arrow left icon
Product type Paperback
Published in Nov 2015
Publisher Packt
ISBN-13 9781785889738
Length 340 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Bhaskar Chaudhary Bhaskar Chaudhary
Author Profile Icon Bhaskar Chaudhary
Bhaskar Chaudhary
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Meet Tkinter FREE CHAPTER 2. Making a Text Editor 3. Programmable Drum Machine 4. A Game of Chess 5. Building an Audio Player 6. Paint Application 7. Multiple Fun Projects 8. Miscellaneous Tips Index

The Tkinter geometry manager

You may recall that we used the pack() method to add widgets to the dummy application that we developed in the previous section. The pack() method is an example of geometry management in Tkinter.

The pack() method is not the only way of managing the geometry in your interface.

In fact, there are three geometry managers in Tkinter that let you specify the position of widgets inside a top-level or parent window.

The three geometry managers are as follows:

  • pack: This is the one that we have used so far. It is simple to use for simpler layouts, but it may get very complex for slightly complex layouts.
  • grid: This is the most commonly used geometry manager that provides a table-like layout of management features for easy layout management.
  • place: This is the least popular, but it provides the best control for the absolute positioning of widgets.

Now, let's have a look at some examples of all the three geometry managers in action.

The pack geometry manager

The pack manager can be a bit tricky to explain in words, and it can best be understood by playing with the code base. Fredrik Lundh, the author of Tkinter, asks us to imagine the root as an elastic sheet with a small opening at the center. The pack geometry manager makes a hole in the elastic sheet that is just large enough to hold the widget. The widget is placed along a given inner edge of the gap (the default is the top edge). It then repeats the process till all the widgets are accommodated. Finally, when all the widgets have been packed in the elastic sheet, the geometry manager calculates the bounding box for all the widgets. It then makes the parent widget large enough to hold all the child widgets.

When packing the child widgets, the pack manager distinguishes between the following three kinds of space:

  • The unclaimed space
  • The claimed but unused space
  • The claimed and used space

The most commonly used options in pack include the following:

  • side: LEFT, TOP, RIGHT, and BOTTOM (these decide the alignment of the widget)
  • fill: X, Y, BOTH, and NONE (these decide whether the widget can grow in size)
  • expand: Boolean values such as tkinter.YES/tkinter.NO, 1/0, True/False
  • anchor: NW, N, NE, E, SE, S, SW, W, and CENTER (corresponding to the cardinal directions)
  • Internal padding (ipadx and ipady) for the padding inside widgets and external padding (padx and pady), which all default to a value of zero

Let's take a look at a demo code that illustrates some of the pack features.

Two of the most commonly used pack options are fill and expand.

Here's the code snippet (code 1.04.py) that will generate a GUI like the one shown in following screenshot:

The pack geometry manager

The following is the code (1.04.py) that generates the preceding GUI:

from tkinter import *
root = Tk()

frame = Frame(root)
# demo of side and fill options
Label(frame, text="Pack Demo of side and fill").pack()
Button(frame, text="A").pack(side=LEFT, fill=Y)
Button(frame, text="B").pack(side=TOP, fill=X)
Button(frame, text="C").pack(side=RIGHT, fill=NONE)
Button(frame, text="D").pack(side=TOP, fill=BOTH)
frame.pack()
# note the top frame does not expand nor does it fill in

# X or Y directions
# demo of expand options - best understood by expanding the root widget and seeing the effect on all the three buttons below.
Label (root, text="Pack Demo of expand").pack()
Button(root, text="I do not expand").pack()
Button(root, text="I do not fill x but I expand").pack(expand = 1)
Button(root, text="I fill x and expand").pack(fill=X, expand=1)
root.mainloop()

The following is a description of the preceding code:

  • When you insert the A button in the root frame, it captures the leftmost area of the frame, expands, and fills the Y dimension. Because the fill option is specified as fill=Y, it claims all the area that it wants and fills the Y dimension of its frame container frame.
  • Because frame is itself packed with a plain pack() method with no mention of a pack option, it takes the minimum space required to accommodate all of its child widgets.
  • If you increase the size of the root window by pulling it down or sideways, you will see that the all the buttons within frame do not fill or expand with the root window.
  • The positioning of the B, C, and D buttons occurs on the basis of the side and fill options specified for each of them.
  • The next three buttons (after B, C, and D) demonstrate the use of the expand option. A value of expand=1 means that the button moves its place on resizing the window. Buttons with no explicit expand options stay at their place and do not respond to changes in the size of their parent container (the root window in this case).
  • The best way to study this piece of code would be to resize the root window to see the effect that it has on various buttons.
  • The anchor attribute (not used in the preceding code) provides a means to position a widget relative to a reference point. If the anchor attribute is not specified, the pack manager places the widget at the center of the available space or the packing box. The other options that are allowed include the four cardinal directions (N, S, E, and W) and a combination of any two directions. Therefore, valid values for the anchor attribute are CENTER (the default value), N, S, E, W, NW, NE, SW, and SE.

Note

The value for most of the Tkinter geometry manager attributes can either be specified in capital letters without quotes (such as side=TOP, anchor=SE) or in small letters within quotes (such as side='top', anchor='se').

We will use the pack geometry manager in some of our projects. Therefore, it will be worthwhile to get acquainted with pack and its options.

The pack manager is ideally suited for the following two kinds of situation:

  • Placing widgets in a top-down manner
  • Placing widgets side by side

Code 1.05.py shows an example of both of these scenarios:

parent = Frame(root)
# placing widgets top-down
Button(parent, text='ALL IS WELL').pack(fill=X)
Button(parent, text='BACK TO BASICS').pack(fill=X)
Button(parent, text='CATCH ME IF U CAN').pack(fill=X)
# placing widgets side by side
Button(parent, text='LEFT').pack(side=LEFT)
Button(parent, text='CENTER').pack(side=LEFT)
Button(parent, text='RIGHT').pack(side=LEFT)
parent.pack()

The preceding code produces a GUI, as shown in the following screenshot:

The pack geometry manager

For a complete pack reference, type the following command in the Python shell:

>>> import tkinter
>>> help(tkinter.Pack)

Tip

Where should you use the pack() geometry manager ?

Using the pack manager is somewhat complicated as compared to the grid method, which will be discussed next, but it is a great choice in situations such as the following ones:

  • Having a widget fill the complete container frame.
  • Placing several widgets on top of each other or side by side (as shown in the preceding screenshot). See code 1.05.py.

Although you can create complicated layouts by nesting widgets in multiple frames, you will find the grid geometry manager more suitable for most of the complex layouts.

The grid geometry manager

The grid geometry manager is easy to understand and perhaps the most useful geometry manager in Tkinter. The central idea of the grid geometry manager is to organize the container frame into a two-dimensional table, which is divided into a number of rows and columns. Each cell in the table can then be targeted to hold a widget. In this context, a cell is an intersection of imaginary rows and columns. Note that in the grid method, each cell can hold only one widget. However, widgets can be made to span multiple cells.

Within each cell, you can further align the position of the widget using the sticky option. The sticky option decides how the widget is expanded. If its container cell is larger than the size of the widget that it contains, the sticky option can be specified using one or more of the N, S, E, and W options or the NW, NE, SW, and SE options.

Not specifying stickiness defaults to stickiness to the center of the widget in the cell.

Let's have a look at a demo code that illustrates some of the features of the grid geometry manager. The code in 1.06.py generates a GUI, as shown in the following screenshot:

The grid geometry manager

The following is the code (1.06.py) that generates the preceding GUI:

from tkinter import *
root = Tk()
Label(root, text="Username").grid(row=0, sticky=W)
Label(root, text="Password").grid(row=1, sticky=W)
Entry(root).grid(row=0, column=1, sticky=E)
Entry(root).grid(row=1, column=1, sticky=E)
Button(root, text="Login").grid(row=2, column=1, sticky=E)
root.mainloop()

The following is a description of the preceding code:

  • Take a look at the grid position defined in terms of the row and column positions for an imaginary grid table spanning the entire frame. See how the use of sticky=W on both the labels makes them stick on the left-hand side, thus resulting in a clean layout.
  • The width of each column (or the height of each row) is automatically decided by the height or width of the widgets in the cell. Therefore, you need not worry about specifying the row or column width as equal. You can specify the width for widgets if you need that extra bit of control.
  • You can use the sticky=NSEW argument to make the widget expandable and fill the entire cell of the grid.

In a more complex scenario, your widgets may span across multiple cells in the grid. To make a grid to span multiple cells, the grid method offers handy options such as rowspan and columnspan.

Furthermore, you may often need to provide some padding between cells in the grid. The grid manager provides the padx and pady options to provide padding that needs to be placed around a widget.

Similarly, the ipadx and ipady options are used for internal padding. These options add padding within the widget itself. The default value of an external and internal padding is 0.

Let's have a look at an example of the grid manager, where we use most of the common arguments to the grid method, such as row, column, padx, pady, rowspan, and columnspan.

Code 1.07.py produces a GUI, as shown in the following screenshot, to demonstrate how to use the grid geometry manager options:

The grid geometry manager

The following is the code (1.07.py) that generates the preceding GUI:

from tkinter import *
parent = Tk()
parent.title('Find & Replace')

Label(parent, text="Find:").grid(row=0, column=0, sticky='e')
Entry(parent, width=60).grid(row=0, column=1, padx=2, pady=2, sticky='we', columnspan=9)

Label(parent, text="Replace:").grid(row=1, column=0, sticky='e')
Entry(parent).grid(row=1, column=1, padx=2, pady=2, sticky='we', columnspan=9)

Button(parent, text="Find").grid(
  row=0, column=10, sticky='e' + 'w', padx=2, pady=2)
Button(parent, text="Find All").grid(
  row=1, column=10, sticky='e' + 'w', padx=2)
Button(parent, text="Replace").grid(row=2, column=10, sticky='e' + 'w', padx=2)
Button(parent, text="Replace All").grid(
  row=3, column=10, sticky='e' + 'w', padx=2)
Checkbutton(parent, text='Match whole word only').grid(
  row=2, column=1, columnspan=4, sticky='w')
Checkbutton(parent, text='Match Case').grid(
  row=3, column=1, columnspan=4, sticky='w')
Checkbutton(parent, text='Wrap around').grid(
  row=4, column=1, columnspan=4, sticky='w')
Label(parent, text="Direction:").grid(row=2, column=6, sticky='w')
Radiobutton(parent, text='Up', value=1).grid(
  row=3, column=6, columnspan=6, sticky='w')
Radiobutton(parent, text='Down', value=2).grid(
  row=3, column=7, columnspan=2, sticky='e')
parent.mainloop()

Note how just 14 lines of the core grid manager code generate a complex layout such as the one shown in the preceding screenshot. On the contrary, developing this with the pack manager would have been much more tedious.

Another grid option that you can sometimes use is the widget.grid_forget() method. This method can be used to hide a widget from the screen. When you use this option, the widget still exists at its former location, but it becomes invisible. The hidden widget may be made visible again, but the grid options that you had originally assigned to the widget will be lost.

Similarly, there is a widget.grid_remove() method that removes the widget, except that in this case, when you make the widget visible again, all of its grid options will be restored.

For a complete grid reference, type the following command in the Python shell:

>>> import tkinter
>>> help(tkinter.Grid)

Tip

Where should you use the grid geometry manager?

The grid manager is a great tool for the development of complex layouts. Complex structures can be easily achieved by breaking the container widget into grids of rows and columns and then placing the widgets in grids where they are wanted. It is also commonly used to develop different kinds of dialog boxes.

Now, we will delve into configuring a grid's column and row sizes.

Different widgets have different heights and widths. So, when you specify the position of a widget in terms of rows and columns, the cell automatically expands to accommodate the widget.

Normally, the height of all the grid rows is automatically adjusted to be the height of its tallest cell. Similarly, the width of all the grid columns is adjusted to be equal to the width of the widest widget cell.

If you then want a smaller widget to fill a larger cell or to stay at any one side of the cell, you can use the sticky attribute on the widget to control this aspect.

However, you can override this automatic sizing of columns and rows by using the following code:

w.columnconfigure(n, option=value, ...)  AND
w.rowconfigure(N, option=value, ...)

Use these to configure the options for a given widget, w, in either the nth column or the nth row, specifying values for the options, minsize, pad, and weight. Note that the numbering of rows begins from 0 and not 1.

The options available are as follows:

Options

Description

minsize

This is the minimum size of a column or row in pixels. If there is no widget in a given column or row, the cell does not appear in spite of this minsize specification.

pad

This is the external padding in pixels that will be added to the specified column or row over the size of the largest cell.

weight

This specifies the relative weight of a row or column and then distributes the extra space. This enables making the row or column stretchable.

For example, the following code distributes two-fifths of the extra space to the first column and three-fifths to the second column:

w.columnconfigure(0, weight=2)
w.columnconfigure(1, weight=3)

The columnconfigure() and rowconfigure() methods are often used to implement the dynamic resizing of widgets, especially on resizing the root window.

Note

You cannot use the grid and pack methods together in the same container window. If you try doing that, your program will raise a _tkinter.TclError error.

The place geometry manager

The place geometry manager is the most rarely used geometry manager in Tkinter. Nevertheless, it has its uses in that it lets you precisely position widgets within its parent frame by using the (x,y) coordinate system.

The place manager can be accessed by using the place() method on all the standard widgets.

The important options for place geometry include the following:

  • Absolute positioning (specified in terms of x=N or y=N)
  • Relative positioning (the key options include relx, rely, relwidth, and relheight)

The other options that are commonly used with place include width and anchor (the default is NW). Refer to the code in 1.08.py for a demonstration of the common place options:

from tkinter import *
root = Tk()
# Absolute positioning
Button(root, text="Absolute Placement").place(x=20, y=10)
# Relative positioning
Button(root, text="Relative").place( relx=0.8, rely=0.2, relwidth=0.5, width=10, anchor=NE)
root.mainloop()

You may not see much of a difference between the absolute and relative positions simply by looking at the code or the window frame. However, if you try resizing the window, you will observe that the button placed does not change its coordinates, while the relative button changes its coordinates and size to accommodate the new size of the root window.

The place geometry manager

For a complete place reference, type the following command in the Python shell:

>>> import tkinter
>>> help(tkinter.Place)

Tip

When should you use the place manager?

The place manager is useful in situations where you have to implement the custom geometry managers, where the widget placement is decided by the end user.

While the pack and grid managers cannot be used together in the same frame, the place manager can be used with any geometry manager within the same container frame.

The place manager is rarely used because, if you use it, you have to worry about the exact coordinates. If you make a minor change to a widget, it is very likely that you will have to change the X-Y values for other widgets as well, which can be very cumbersome.

We will not use the place manager in our projects. However, knowing that options for coordinate-based placement exist can be helpful in certain situations.

This concludes our discussion on geometry management in Tkinter.

In this section, you had a look at how to implement the pack, grid, and place geometry managers. You also understood the strengths and weaknesses of each geometry manager.

You learned that pack is suitable for a simple side-wise or top-down widget placement. You also learned that the grid manager is best suited for the handling of complex layouts. You saw examples of the place geometry manager and explored the reasons behind why it is rarely used.

You should now be able to plan and execute different layouts for your programs using these Tkinter geometry managers.

You have been reading a chapter from
Tkinter GUI Application Development Blueprints
Published in: Nov 2015
Publisher: Packt
ISBN-13: 9781785889738
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image