One of the things that makes the color picker GUI ugly is the fact that everything is arranged top to bottom. Tkinter uses this layout by default, but we can usually come up with something better.

To see how, let's revisit the example from Figure 14.8, on page 302, placing the label and button horizontally. We tell Tkinter to do this by providing a side argument to the pack method. The code to do this is shown here, and the result can be seen in Figure 14.11, on the following page:

Download gui/

from Tkinter import * window = Tk() frame = Frame(window) frame.pack()

Figure 14.11: A window with horizontal layout label = Label(frame, text="Name")


entry = Entry(frame)



Setting side to "left" tells Tkinter that the leftmost part of the label is to be placed next to the left edge of the frame, and then the leftmost part of the entry field is placed next to the right edge of the label—in short, that widgets are to be packed using their left edges. We could equally well pack according to the right, top, or bottom edges, or we could mix packings (though that can quickly become confusing).

For even more control of our window layout, we can use a different layout manager called grid. As its name implies, it treats windows and frames as grids of rows and columns. To add the widget to the window, we call grid instead of pack. Do not call both! The grid call can take several parameters, which are shown in Figure 14.12, on the next page.

in the following code, we place the label in the upper left (row 0, column 0) and the entry field in the lower right (row 1, column 1). As you can see in Figure 14.13, on page 313, this leaves the bottom-left and upper-right corners empty:

Download gui/

from Tkinter import * window = Tk() frame = Frame(window) frame.pack()

label = Label(frame, text="Name:") label.grid(row=0, column=0) entry = Entry(frame) entry.grid(row=1, column=1) window.mainloop()

Parameter Description row The number of the row to insert the widget into. Row numbers begin at 0. column The number of the column to insert the widget into. Col umn numbers begin at 0. rowspan The number of rows the widget occupies. The default is 1. columnspan The number of columns the widget occupies. The default is 1.

Figure 14.12: grid() parameters

Was this article helpful?

0 0

Post a comment