Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

These options are available for the selectmode parameter:


SINGLE—Select only one item at a time.
BROWSE—Select only one item but the items can be moved in the list.
MULTIPLE—Select multiple items by clicking them one at a time.
EXTENDED—Select multiple items by using the Shift and Control keys while clicking items.

After you create the Listbox widget, you need to add items to the list. You do that with the
insert() method, as shown here:


Click here to view code image


self.listbox1.insert(END, 'Item One')

The first parameter defines the index location in the list where the new item should be inserted. You
can use the keyword END to place the new item at the end of the list. If you have a lot of items to add
to the Listbox widget, you can place them in a list object and use a for loop to insert them all at
once, as in the following example:


Click here to view code image


items = ['Item One', 'Item Two', 'Item Three']
for item in items:
self.listbox1.insert(END, item)

Retrieving the selected items from the Listbox widget is a two-step process. First, you use the
curselection() method to retrieve a tuple that contains the index of the selected items (starting
at 0 ):


Click here to view code image


items = self.listbox1.curselection()

Once you have the tuple that contains the index values, you use the get() method to retrieve the text
value of the item at that index location:


Click here to view code image


for item in items:
strItem = self.listbox1.get(item)

Listing 18.8 shows the script1808.py file, which demonstrates how to use the Listbox widget
in your programs.


LISTING 18.8 The script1808.py Program Code


Click here to view code image


#!/usr/bin/python3
from tkinter import *

class Application(Frame):
"""Build the basic window frame template"""

def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
Free download pdf