As those who have followed this series over the last few weeks might have noted, I’ve racked my brain trying to get around the Tkinter Listbox. For those not familiar with the Tkinter Listbox, it’s a GUI widget which allow for selection from a list of items, but the items can only be one word long. I’ve wondered why they put it together so you can only use one word in the selection. It seems so totally useless. Now I think I figured it out.
I’ve been working on a camera application. The API I’m using has a lot of dictionaries to set modes on the camera. When making the UI for the camera I found why Tkinter was so interested in single word selections is dictionary keys.
In a new file add the following code:
from tkinter import * METER_MODES = {'Auto':1,'Spot':2,'Matrix':4,'Backlit':8} #controller def meterModeSelected(event): index = meterMode_listbox.curselection() selection = meterMode_listbox.get(index[0]) modelabel.set(selection) # a method to take a dictionary and return its keys as a space delimited string def listboxlist(aDictionary): x="" for i in list(aDictionary): x=x+i+" " return x #view #make the window root=Tk() root.title('Camera demo #1') #make the frame frame = Frame(root) frame.grid(row=0, column=0) #label modelabel = StringVar() modelabel.set('Meter Modes') label = Label(frame,textvariable = modelabel).grid(row=0, column=0) #meter mode listbox meterMode_list = StringVar() meter_modes = listboxlist(METER_MODES) #extract a list as a string from the dictionary meterMode_list.set(meter_modes) meterMode_listbox = Listbox(frame,listvariable=meterMode_list, width = 10) meterMode_listbox.grid(row = 1, column = 0) meterMode_listbox.bind('',meterModeSelected) #main loop mainloop()
Line 3 sets up a dictionary, which we use in line 31 to call the function listboxlist
in lines 10-14. Dictionaries when cast as lists make a list of the dictionary keys. This for loop changes the list into a string with spaces, exactly what Listbox uses.
In short, the Listbox is a quick way to select from a dictionary or list. It still isn’t what we need for Popper’s Penguins, but at least we know what the reason is for Listbox’s design.
Leave a Reply