[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Programming Listboxes


Listboxes are straightforward to use, but they are populated and processed in somewhat
unique ways compared to the widgets we’ve seen so far. Many listbox calls accept a
passed-in index to refer to an entry in the list. Indexes start at integer 0 and grow higher,
but tkinter also accepts special name strings in place of integer offsets: end to refer to
the end of the list, active to denote the line selected, and more. This generally yields
more than one way to code listbox calls.


For instance, this script adds items to the listbox in this window by calling its insert
method, with successive offsets (starting at zero—something the enumerate built-in
could automate for us):


list.insert(pos, label)
pos += 1

But you can also fill a list by simply adding items at the end without keeping a position
counter at all, with either of these statements:


list.insert('end', label) # add at end: no need to count positions
list.insert(END, label) # END is preset to 'end' inside tkinter

The listbox widget doesn’t have anything like the command option we use to register
callback handlers for button presses, so you either need to fetch listbox selections while
processing other widgets’ events (e.g., a button press elsewhere in the GUI) or tap into
other event protocols to process user selections. To fetch a selected value, this script
binds the left mouse button double-click event to a callback handler method
with bind (seen earlier on this tour).


In the double-click handler, this script grabs the selected item out of the listbox with
this pair of listbox method calls:


index = self.listbox.curselection() # get selection index
label = self.listbox.get(index) # fetch text by its index

Here, too, you can code this differently. Either of the following lines has the same effect;
they get the contents of the line at index 'active'—the one selected:


label = self.listbox.get('active') # fetch from active index
label = self.listbox.get(ACTIVE) # ACTIVE='active' in tkinter

For illustration purposes, the class’s default runCommand method prints the value selec-
ted each time you double-click an entry in the list—as fetched by this script, it comes
back as a string reflecting the text in the selected entry:


C:\...\PP4E\Gui\Tour> python scrolledlist.py
You selected: Lumberjack-2
You selected: Lumberjack-19
You selected: Lumberjack-4
You selected: Lumberjack-12

Listboxes can also be useful input devices even without attached scroll bars; they accept
color, font, and relief configuration options. They also support both single and multiple


524 | Chapter 9: A tkinter Tour, Part 2

Free download pdf