File: pyedit-products/unzipped/PP4E/Gui/Tour/scrolledlist.py

"""
================================================================
A simple customizable vertical-only scrolled listbox component.
The caller must santize any non-BMP Unicode chars in Tk's ~8.6.
See also frigcal's variant, with support for other click types.
Added here, Apr-2017: horizscroll, for double-scrolled lists,
and listfont for customizable text font: (family, size, style).
================================================================
"""

from tkinter import *


class ScrolledList(Frame):
    def __init__(self, options, parent=None, horizscroll=False, listfont=None):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)                   # make me expandable
        self.makeWidgets(options, horizscroll, listfont)

    def handleList(self, event):
        index = self.listbox.curselection()                # on list double-click
        label = self.listbox.get(index)                    # fetch selection text
        self.runCommand(label)                             # and call action here
                                                           # or get(ACTIVE)
    def makeWidgets(self, options, horizscroll, listfont):
        sbar = Scrollbar(self)
        list = Listbox(self, relief=SUNKEN)
        if listfont:
            list.config(font=listfont)
        if horizscroll:
            hbar = Scrollbar(self, orient='horizontal')

        sbar.config(command=list.yview)                    # xlink sbar and list
        list.config(yscrollcommand=sbar.set)               # move one moves other
        if horizscroll:
            hbar.config(command=list.xview) 
            list.config(xscrollcommand=hbar.set)

        sbar.pack(side=RIGHT, fill=Y)                      # pack first=clip last
        if horizscroll:
            hbar.pack(side=BOTTOM, fill=X)
        list.pack(side=LEFT, expand=YES, fill=BOTH)         # list clipped first

        pos = 0
        for label in options:                              # add to listbox
            list.insert(pos, label)                        # or insert(END,label)
            pos += 1                                       # or enumerate(options)

       #use defaults
       #list.config(selectmode=SINGLE, setgrid=1)          # select,resize modes
            
        list.bind('<Double-1>', self.handleList)           # set event handler
        self.listbox = list

    def runCommand(self, selection):                       # redefine me lower
        print('You selected:', selection)


if __name__ == '__main__':
    options = (('Lumberjack-%s' % x) for  x in range(20))  # or map/lambda, [...]
    options = list(options) + ['   '.join("And I'm okay!")]
    ScrolledList(options, horizscroll=True).mainloop()



[Home page] Books Code Blog Python Author Train Find ©M.Lutz