Tkinter: Making a listbox that can change variables on selection

[亡魂溺海] 提交于 2020-01-16 19:01:09

问题


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.


回答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

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.



来源:https://stackoverflow.com/questions/15886951/tkinter-making-a-listbox-that-can-change-variables-on-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!