Tkinter绑定ListboxSelect可以在框架中与多个Listbox一起使用

问题描述 投票:0回答:1

我从此链接中将函数绑定到ListboxGetting 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()
python tkinter listbox bind
1个回答
0
投票

创建列表框`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)
© www.soinside.com 2019 - 2024. All rights reserved.