【问题标题】:Tkinter binding ListboxSelect to function with multiple Listboxes in frame [duplicate]Tkinter绑定ListboxSelect以在框架中使用多个列表框[重复]
【发布时间】:2020-06-05 18:23:50
【问题描述】:

我从这个链接中得到了将函数绑定到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()

【问题讨论】:

  • select()select2()函数中listBox应该是event吗?

标签: python tkinter listbox bind


【解决方案1】:

您只需要在创建列表框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)

【讨论】:

    猜你喜欢
    • 2020-06-13
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多