组合框清除无关的列表框tkinter python

2024-06-25 05:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常简单的图形用户界面程序用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中点击了几个项目,然后点击按钮。 我得到的输出与预期一致:

^{pr2}$

我现在从ComboBox中选择一个值,ListBox中的选择突然消失了。点击按钮显示列表框中未选择任何值:

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

我的问题是:为什么选择组合框项会清除列表框的选择?他们没有任何关系,所以这个虫子真的让我困惑!在


Tags: toinfromimportselfroot图形用户界面pack
1条回答
网友
1楼 · 发布于 2024-06-25 05:23:16

我终于找到了答案。我把这个问题留在这里,以防别人发现。在

问题不在组合框中,而是在列表框中。如果我使用两个(不相关的)列表框,这就变得很清楚了。当焦点改变时,两个列表框的选择将被清除。 根据this question及其公认的答案,我发现将exportselection=0添加到列表框会禁用导出选择的X选择机制。在

来自effbot listbox关于X选择机制:selects something in one listbox, and then selects something in another, the original selection disappears.

相关问题 更多 >