从列表框中选择,从另一个列表框中选择填充

问题描述 投票:-1回答:2

我有两个列表框。单击第一个列表框中的项目将在第二个列表框中插入信息。

当我点击其中一个插入的项目时,出现错误。

列表框定义为:

list_1 = Listbox(root,selectmode=SINGLE)
list_2 = Listbox(root,selectmode=SINGLE)

要获取所选项目:

list_1.bind('<<ListboxSelect>>',CurSelect)

指的是:

def CurSelect(evt):
        list_2.delete(0,END)
        selected = list_1.get(list_1.curselection())

        for i in range(2):
            list_2.insert(END,i)

单击list_1中的一个项目会在list_2中插入项目。

如果我选择了List_2的项目,则会显示:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\XXX\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call
__
    return self.func(*args)
  File "unbenannt.py", line 28, in CurSelect
    selected = liste.get(liste.curselection())
  File "C:\Users\XXX\Anaconda3\lib\tkinter\__init__.py", line 2792, in get
    return self.tk.call(self._w, 'get', first)
_tkinter.TclError: bad listbox index "": must be active, anchor, end, @x,y, or a
 number

在第一个Listbox中选择时遇到了这种问题,但是用<< ListboxSelect >>解决了它。

以前单击第二个列表框中的项目有效,但从那以后我没有更改任何内容。

完整代码示例:

from tkinter import *

class Code():
    def __init__(self):
        Code.Window(self)

    def Window(self):
        root = Tk()

        scrollbar = Scrollbar(root)
        scrollbar.grid(row=4,rowspan=3,column=1,sticky=N+S+W)

        liste = Listbox(root,selectmode=SINGLE,width=12,yscrollcommand=scrollbar.set)
        liste.grid(row=4,rowspan=3,column=0)

        for j in range(2):
            liste.insert(END,j+5)

        scrollbar.config(command=liste.yview)
        scrollbar_2 = Scrollbar(root)
        scrollbar_2.grid(row=4,rowspan=3,column=3,sticky=N+S+W)

        eintrag = Listbox(root,selectmode=SINGLE,yscrollcommand=scrollbar_2.set)
        eintrag.grid(row=4,rowspan=3,column=2,sticky=W)

        def CurSelect(evt):
            eintrag.delete(0,END)
            selected = liste.get(liste.curselection())
            for i in range(2):
                eintrag.insert(END,str(i)+str(selected))

        liste.bind('<<ListboxSelect>>',CurSelect)

        root.mainloop()

Code()

这个例子没有任何用处,但无论如何都会出现问题。

python tkinter listbox
2个回答
0
投票

问题是默认情况下,一次只能有一个列表框可供选择。当您在第二个列表框中选择某些内容时,将从第一个列表框中删除该选择。当发生这种情况时,您的绑定会触发,但您的绑定函数会假定liste.curselection()返回非空字符串。

最简单的解决方案是允许两个列表框同时进行选择。你可以通过将exportselection属性设置为False来实现:

liste = Listbox(..., exportselection=False)
...
eintrag = Listbox(..., exportselection=False)

0
投票

该错误引发,因为当右侧列表框eintrag获得焦点时,左侧列表框中选择的任何项目liste将被取消选择并调用'<<ListboxSelect>>'的事件回调,其中假设liste.curselection()永远不会是空的,这在这种特殊情况下是不真实的,因此liste.get(liste.curselection())会在尝试获取""索引中的项目时抛出错误。

使用if嵌套整个事件处理程序可以解决此问题:

def CurSelect(evt):
    if liste.curselection(): # To call below statements only when liste has a selected item
        eintrag.delete(0,END)
        selected = liste.get(liste.curselection())
        for i in range(2):
            eintrag.insert(END,str(i)+str(selected))
© www.soinside.com 2019 - 2024. All rights reserved.