ComboBox 清空无关的 ListBox tkinter python

1 投票
1 回答
1798 浏览
提问于 2025-04-18 10:54

我有一个用Python和tkinter写的非常简单的图形界面程序:

from Tkinter import *
from ttk import Combobox

class TestFrame(Frame):

    def __init__(self, root, vehicles):

        dropdownVals = ['test', 'reallylongstring', 'etc']
        listVals = ['yeaaaah', 'mhm mhm', 'untz untz untz', 'test']

        self.dropdown = Combobox(root, values=dropdownVals)
        self.dropdown.pack()

        listboxPanel = Frame(root)

        self.listbox = Listbox(listboxPanel, selectmode=MULTIPLE)        
        self.listbox.grid(row=0, column=0)

        for item in listVals:
            self.listbox.insert(END, item) # Add params to list

        self.scrollbar = Scrollbar(listboxPanel, orient=VERTICAL)
        self.listbox.config(yscrollcommand=self.scrollbar.set) # Connect list to scrollbar
        self.scrollbar.config(command=self.listbox.yview) # Connect scrollbar to list
        self.scrollbar.grid(row=0, column=1, sticky=N+S)

        listboxPanel.pack()

        self.b = Button(root, text='Show selected list values', command=self.print_scroll_selected)
        self.b.pack()

        root.update()

    def print_scroll_selected(self):

        listboxSel = map(int, self.listbox.curselection()) # Get selections in listbox

        print '=========='
        for sel in listboxSel:
            print self.listbox.get(sel)
        print '=========='
        print ''

# Create GUI
root = Tk()
win = TestFrame(root, None)
root.mainloop();

这个图形界面看起来是这样的:

我在ListBox里点击了几个项目,然后按下了按钮。得到的输出是我预期的:

==========
untz untz untz
==========

==========
yeaaaah
untz untz untz
==========

现在我从ComboBox中选择一个值,突然间ListBox中的选择就消失了。按下按钮后发现ListBox里没有任何值被选中:

==========
==========

我的问题是:为什么选择ComboBox中的一个项目会清除ListBox中的选择?它们之间没有任何关系,所以这个问题让我很困惑!

1 个回答

3

我终于找到了答案。把这个问题留在这里,以防其他人也能找到它。

问题不在于组合框(ComboBox),而是在列表框(ListBox)上。如果我使用两个(没有关系的)列表框,就会很明显。当焦点切换时,选择的内容会被清空。通过这个问题和它的被接受答案,我发现给列表框加上exportselection=0可以关闭X选择机制,这样选择的内容就不会被导出。

关于X选择机制的更多信息,可以参考effbot的列表框,它提到:在一个列表框中选择某个东西,然后在另一个列表框中选择另一个东西,原来的选择就会消失。

撰写回答