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

(yzsuai) #1

selection modes. The default mode allows only a single item to be selected, but the
selectmode argument supports four settings: SINGLE, BROWSE, MULTIPLE, and EXTENDED
(the default is BROWSE). Of these, the first two are single selection modes, and the last
two allow multiple items to be selected.


These modes vary in subtle ways. For instance, BROWSE is like SINGLE, but it also allows
the selection to be dragged. Clicking an item in MULTIPLE mode toggles its state without
affecting other selected items. And the EXTENDED mode allows for multiple selections
and works like the Windows file explorer GUI—you select one item with a simple click,
multiple items with a Ctrl-click combination, and ranges of items with Shift-clicks.
Multiple selections can be programmed with code of this sort:


listbox = Listbox(window, bg='white', font=('courier', fontsz))
listbox.config(selectmode=EXTENDED)
listbox.bind('<Double-1>', (lambda event: onDoubleClick()))

# onDoubeClick: get messages selected in listbox
selections = listbox.curselection() # tuple of digit strs, 0..N-1
selections = [int(x)+1 for x in selections] # convert to ints, make 1..N

When multiple selections are enabled, the curselection method returns a list of digit
strings giving the relative numbers of the items selected, or it returns an empty tuple if
none is selected. Really, this method always returns a tuple of digit strings, even in
single selection mode (we don’t care in Example 9-9, because the get method does the
right thing for a one-item tuple, when fetching a value out of the listbox).


You can experiment with the selection alternatives on your own by uncommenting the
selectmode setting in Example 9-9 and changing its value. You may get an error on
double-clicks in multiple selection modes, though, because the get method will be
passed a tuple of more than one selection index (print it out to see for yourself). We’ll
see multiple selections in action in the PyMailGUI example later in this book (Chap-
ter 14), so I’ll pass on further examples here.


Programming Scroll Bars


Perhaps the deepest magic in the Example 9-9 script, though, boils down to two lines
of code:


sbar.config(command=list.yview) # call list.yview when I move
list.config(yscrollcommand=sbar.set) # call sbar.set when I move

The scroll bar and listbox are effectively cross-linked to each other through these con-
figuration options; their values simply refer to bound widget methods of the other. By
linking like this, tkinter automatically keeps the two widgets in sync with each other
as they move. Here’s how this works:



  • Moving a scroll bar invokes the callback handler registered with its command option.
    Here, list.yview refers to a built-in listbox method that adjusts the listbox display
    proportionally, based on arguments passed to the handler.


Listboxes and Scrollbars| 525
Free download pdf