madprogramer
madprogramer

Reputation: 609

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(2,"morestuff")
a = 0

How can I make that procedure run, each time I select a different part of the listbox? For example I first click "stuff" and then click "morestuff". Clicking "stuff" sets a to 1 and clicking "morestuff" sets a to 0 again.

Upvotes: 0

Views: 3931

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

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

class Example(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)

    def on_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.

Upvotes: 3

Related Questions