This is a section of an app that’s giving me trouble: When I click ‘select category’, it should output a 1 when ‘Cheese’ is selected, but it always outputs 0. Can someone tell me why, and give me a fix? I know I should organize this as an object, but I’d like to treat ‘categories’ as an attribute of the main Tkinter object. I’m new to python and Tkinter, and don’t know how I’d access an attribute. Thanks.
import Tkinter
root = Tkinter.Tk()
root.title('Test App')
mainFrame = Tkinter.Frame(root)
def mainWindow():
categories = [['Bread','Rye','Wheat'],['Cheese','Feta']]
categoryListbox = Tkinter.Listbox()
for category in categories:
categoryListbox.insert('end', category[0])
categoryListbox.pack()
activeIndex = categoryListbox.index('active')
selectCategoryButton = Tkinter.Button(text="Select Category", command= lambda: selectCategory(activeIndex))
selectCategoryButton.pack()
def selectCategory(activeIndex):
print activeIndex
root.mainloop()
You only retrieve the selected index once:
All future selections refer to this index. You can change your lambda so it retrieves the current selected index instead of referring to the old one: