Tkinter 绑定 ListboxSelect 以在框架中使用多个列表框

Tkinter binding ListboxSelect to function with multiple Listboxes in frame

我从这个 link 得到了将函数绑定到 Listbox 的想法: Getting a callback when a Tkinter Listbox selection is changed?

仅使用一个 Listbox 效果很好。 一旦我尝试在页面上引入第二个 Listbox 并将其绑定到第二个函数,我想象的功能就消失了。

显然,如果在第一个列表中的项目已被选中的情况下选择第二个列表中的项目,则会从列表一中移除选择。谁能帮我解决这个问题?

这是我的示例代码:

import tkinter as tk

window = tk.Tk()
#generic window size, showing listbox is smaller than window
window.geometry("600x480")

frame = tk.Frame(window)
frame.pack()

def select(evt):
    event = evt.widget
    output = []
    selection = event.curselection()
    #.curselection() returns a list of the indexes selected
    #need to loop over the list of indexes with .get()
    for i in selection:
        o = listBox.get(i)
        output.append(o)
    print(output)

def select2(evt):
    event = evt.widget
    output = []
    selection = event.curselection()
    #.curselection() returns a list of the indexes selected
    #need to loop over the list of indexes with .get()
    for i in selection:
        o = listBox.get(i)
        output.append(o)
    print(output)

listBox = tk.Listbox(frame, width=20, height = 5, selectmode='multiple')

listBox.bind('<<ListboxSelect>>',select)
listBox.pack(side="left", fill="y")
scrollbar = tk.Scrollbar(frame, orient="vertical")
scrollbar.config(command=listBox.yview)
scrollbar.pack(side="right", fill="y")
listBox.config(yscrollcommand=scrollbar.set)

for x in range(100):
    listBox.insert('end', str(x))


listBox2 = tk.Listbox(frame, width=20, height = 5, selectmode='multiple')

listBox2.bind('<<ListboxSelect>>',select2)
listBox2.pack(side="left", fill="y")
scrollbar2 = tk.Scrollbar(frame, orient="vertical")
scrollbar2.config(command=listBox.yview)
scrollbar2.pack(side="right", fill="y")
listBox2.config(yscrollcommand=scrollbar.set)

for x in range(100):
    listBox2.insert('end', str(x))



window.mainloop()

您只需要在创建列表框 tk.Listbox(frame,...) 时添加参数 exportselection=False。然后您的列表框将继续被选中。

listBox = tk.Listbox(frame, width=20, height = 5, selectmode='multiple', exportselection=False)

listBox2 = tk.Listbox(frame, width=20, height = 5, selectmode='multiple', exportselection=False)