如何从两个Listbox中同时选择?

2022-01-16 00:00:00 python tkinter listbox

问题描述

from Tkinter import *


master = Tk()

listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")

for item in ["one", "two", "three", "four"]:
    listbox.insert(END, item)

listbox2 = Listbox(master)
listbox2.pack()
listbox2.insert(END, "a list entry")

for item in ["one", "two", "three", "four"]:
    listbox2.insert(END, item)

master.mainloop()

上面的代码创建了一个带有两个列表框的 tkinter 窗口.但是,如果您想从两者中检索值,则会出现问题,因为一旦您在其中一个中选择了一个值,它就会取消选择您在另一个中选择的任何内容.

The code above creates a tkinter window with two listboxes. But there's a problem if you want to retrieve the values from both because, as soon as you select a value in one, it deselects whatever you selected in the other.

这只是开发人员必须忍受的限制吗?

Is this just a limitation developers have to live with?


解决方案

简答:将所有列表框小部件的 exportselection 属性的值设置为 False 或零.

Short answer: set the value of the exportselection attribute of all listbox widgets to False or zero.

来自 a列表框小部件的pythonware概述:

默认情况下,选择导出X选择机制.如果你有多个列表框屏幕,这真的把事情搞砸了对于可怜的用户.如果他选择一个列表框中的东西,然后在另一个中选择某些东西,原始选择被清除.它是通常禁用此功能是个好主意这种情况下的机制.在里面下面的例子,三个列表框是在同一个对话框中使用:

By default, the selection is exported to the X selection mechanism. If you have more than one listbox on the screen, this really messes things up for the poor user. If he selects something in one listbox, and then selects something in another, the original selection is cleared. It is usually a good idea to disable this mechanism in such cases. In the following example, three listboxes are used in the same dialog:

b1 = Listbox(exportselection=0)
for item in families:
    b1.insert(END, item)

b2 = Listbox(exportselection=0)
for item in fonts:
    b2.insert(END, item)

b3 = Listbox(exportselection=0)
for item in styles:
    b3.insert(END, item)

tk 小部件的权威文档基于 Tcl 语言而不是 python,但很容易翻译成 python.exportselection 属性可以在 标准选项手册页.

The definitive documentation for tk widgets is based on the Tcl language rather than python, but it is easy to translate to python. The exportselection attribute can be found on the standard options manual page.

相关文章