Tkinter: Making A Listbox That Can Change Variables On Selection
Now I made a procedure that activates on the click of a button. Now say I have a listbox called: selection = Tkinter.Listbox(b_action) selection.insert(1,'stuff') selection.insert(
Solution 1:
You can create a dictionary mapping the actual listbox values with your alternate values (eg: {"stuff": 1, "morestuff": 2}
. Next, create a binding on <<ListboxSelect>>
. In the function called from that binding, get the currently selected item, use that to look up the other value, and store that value in your variable.
Here's an example:
import Tkinter as tk
classExample(tk.Frame):
def__init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.label = tk.Label(self)
self.selection = tk.Listbox(self, width=40)
self.label.pack(side="top", fill="x", expand=False)
self.selection.pack(side="top", fill="both", expand=True)
self.data = {"stuff": 1, "morestuff": 2}
self.selection.insert("end", "stuff", "morestuff")
self.selection.bind("<<ListboxSelect>>", self.on_listbox_select)
defon_listbox_select(self, event):
i = self.selection.curselection()[0]
text = self.selection.get(i)
self.label.configure(text="new value: %s (%s)" % (self.data[text], text))
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
If you only want to set the variable to the index of the selected item, you don't need the dictionary. It wasn't clear from your question whether you wanted the index of what was selected, or some different value that is associated with the listbox item.
Post a Comment for "Tkinter: Making A Listbox That Can Change Variables On Selection"