Thursday, July 26, 2012

Tkinter Listbox States Demo

The code is based on the Tcl states.tcl demo. It presents a simple Listbox populated with the names of the US States. Currently there is no ttk.Listbox; however, the ttk.Scrollbar can be used with the tkinter Listbox widget.





# File: listboxstates.py
# References:
#    http://infohost.nmt.edu/tcc/help/pubs/tkinter//listbox.html
#    http://www.tcl.tk/man/tcl8.5/TkCmd/listbox.htm
#    http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_scrollbar.htm

from tkinter import *
from tkinter import ttk
from demopanels import MsgPanel, SeeDismissPanel

STATES = ( 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
         'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia',
         'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa',
         'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland',
         'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri',
         'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey',
         'New Mexico', 'New York', 'North Carolina', 'North Dakota',
         'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', "Rhode Island",
         "South Carolina", "South Dakota", 'Tennessee', 'Texas', 'Utah',
         'Vermont', 'Virginia', 'Washington', "West Virginia", 'Wisconsin',
         'Wyoming'  )

class ListboxStatesDemo(ttk.Frame):
    
    def __init__(self, isapp=True, name='listboxstatesdemo'):
        ttk.Frame.__init__(self, name=name)
        self.pack(expand=Y, fill=BOTH)
        self.master.title('Listbox States Demo')
        self.isapp = isapp
        self._create_widgets()
        
    def _create_widgets(self):
        if self.isapp:
            MsgPanel(self, 
                     ["A listbox containing the 50 states is displayed below, along with a scrollbar.  ",
                      "You can scan the list either using the scrollbar or by scanning.\n\n",
                      "To scan, click in the listbox, hold the left mouse button down, and drag up or down."])
            
            SeeDismissPanel(self)
        
        self._create_demo_panel()
        
    def _create_demo_panel(self):
        demoPanel = ttk.Frame(self)
        demoPanel.pack(side=TOP, fill=BOTH, expand=Y)
                
        self._states_lb(demoPanel)        
                
    def _states_lb(self, parent):
        f = ttk.Frame(parent, borderwidth='.5c')
        sb = ttk.Scrollbar(orient=VERTICAL)

        # 'setgrid' allows the widget to
        # control the resize dimension (i.e. character
        # vs pixel) used by the grid in the top-level window
        # 'height' = number of lines (not pixels)
        lb = Listbox(setgrid=True, height=12)

        sb['command'] = lb.yview
        lb['yscroll'] = sb.set
        
        lb.insert(END, *STATES)
        
        sb.pack(in_=f, side=RIGHT, fill=Y)
        lb.pack(in_=f, side=LEFT, fill=BOTH, expand=Y)

        f.pack()

if __name__ == '__main__':
    ListboxStatesDemo().mainloop()