Page 73 - Programming the Raspberry Pi Getting Started with Python
P. 73
The way to do this is to use a special “variable” like we did in the temperature converter example.
In the following example, we use a StringVar, but if the values of onvalue and offvalue were
numbers, we could use an IntVar instead.
Listbox
To display a list of items from which one or multiple items can be selected, a Listbox is used (refer to
the center of Figure 7-5). Here’s an example:
In this case, it just displays a list of colors. Each string has to be added to the list individually. The
word END indicates that the item should go at the end of the list.
You can control the way selections are made on the Listbox using the selectmode property, which
can be set to one of the following:
• SINGLE Only one selection at a time.
• BROWSE Similar to SINGLE, but allows selection using the mouse. This appears to be
indistinguishable from SINGLE in Tkinter on the Pi.
• MULTIPLE SHIFT-click to select more than one row.
• EXTENDED Like MULTIPLE, but also allows the CTRL-SHIFT-click selection of ranges.
Unlike with other widgets that use StringVar or some other type of special variable to get values in
and out, to find out which items of the Listbox are selected, you have to ask it using the method
curselection. This returns a collection of selection indexes. Thus, if the first, second, and fourth
items in the list are selected, you will get a list like this:
When selectmode is SINGLE, you still get a list back, but with just one value in it.
Spinbox
Spinboxes provide an alternative way of making a single selection from a list:
The get method returns the currently displayed item in the Spinbox, not its selection index.
Layouts
Laying out the different parts of your application so that everything looks good, even when you resize
the window, is one of the most tricky parts of building a GUI.
You will often find yourself putting one kind of layout inside another. For example, the overall
shape of the “kitchen sink” application is a 3×3 grid, but within that grid is another frame for the two
radio buttons:
This approach is quite common, and it is a good idea to sketch out the layout of your controllers on
paper before you start writing the code.