Last week I had an OptionMenu which loaded a list quite large, It was alot for an OptionMenu so I decided to use a listbox but since I'm new at tkinter I had to figure out how to make one, so after a while of searching for an example, I came across a simple code the problem was that it was just a listbox with a list and scroll bar, I still had to figure out how to load a list and how to retrieve the selected value. Then again went searching and after putting all together here is what I made.
"""Listbox widget with scrollbar
"""Includes the insertion and selection of items
"""Limits the selection to one, so it shows it on a separate frame.
from tkinter import *
from tkinter import ttk
def addopcs(l):
l.delete(0,END)
for i in range(1,101):
l.insert('end', 'New Selection %d' % i)
def valid(lb,root):
try:
tl = Toplevel(root, takefocus=True, padx=10, pady=10)
df = Frame(tl).pack()
value = lb.get(lb.curselection()[0])
except IndexError:
value = "None selected"
lbl = Label(tl,text=value).pack(side=LEFT)
root = Tk()
changeButton = Button(root, text="Change", command=lambda : addopcs(l)).pack(side=BOTTOM)
lf = LabelFrame(root, text="Listbox", padx=10, pady=5, relief=GROOVE)
l = Listbox(lf, height=5, selectmode=SINGLE)
l.pack(side=LEFT, fill=BOTH, expand=1)
s = Scrollbar(lf, orient=VERTICAL, command=l.yview)
s.pack(side=RIGHT, fill=Y)
l['yscrollcommand'] = s.set
chooseButton = Button(root, text="Choose", command=lambda lb=l: valid(lb,root))
chooseButton.pack(side=BOTTOM)
lf.pack(fill=BOTH, expand=YES, side=LEFT, padx=10, pady=10)
for i in range(1,101):
l.insert('end', 'Line %d of 100' % i)
root.mainloop()
here is the output...
For some of you this may look simple and mundane,
but I believe there has to be someone that could save at least a couple of hours.
Remember : Python 3.2, tkinter.
Comments, Suggestions are Welcome.