首页 > 解决方案 > Tkinter 列表框转到错误的功能

问题描述

在我的代码中,我必须列出绑定到 2 个不同函数的框。这是代码:

from tkinter import *
import string

class App:

    def change_dropdown(self, *args):
        print(self.Lb1.curselection())
        self.Lb2.insert(self.count, self.choices[self.Lb1.curselection()[0]])
        self.count+=1

    def delete_dropdown_selected(self, *args):
        print(self.Lb2.curselection())


    def __init__(self, master):

        self.count = 0

        self.left = Frame(master)
        self.left.config()
        self.left.pack(side=LEFT)

        self.choices = []

        self.yscroll = Scrollbar(master, orient=VERTICAL)

        self.Lb1 = Listbox(self.left, selectmode=SINGLE, yscrollcommand=self.yscroll.set, font=50, bd=2)
        self.Lb2 = Listbox(self.left, selectmode=SINGLE, bd=2)

        for j in range(2):
            for i in range(26):
               self.Lb1.insert(i,string.ascii_lowercase[i])
               self.choices.append(string.ascii_letters[i])

        self.Lb1.config(width=50, height=30)
        self.Lb1.pack(side=TOP, fill=BOTH, expand=1)
        self.Lb2.config(font=30, width=50, height=10)
        self.Lb2.pack(side=BOTTOM, fill=BOTH, expand=1, pady=10)
        self.Lb2.bind('<<ListboxSelect>>', self.delete_dropdown_selected)
        self.Lb1.bind('<<ListboxSelect>>', self.change_dropdown)
        self.yscroll.pack(side=LEFT, fill=Y)
        self.yscroll.config(command=self.Lb1.yview)


root = Tk()
root.resizable(width=False, height=False)
app = App(root)
root.mainloop()

问题是当我单击 Lb2 中的一个项目时,它会转到change_dropdown()而不是delete_dropdown_selected()。我不明白为什么,因为我在这里指定它:

self.Lb2.bind('<<ListboxSelect>>', self.delete_dropdown_selected)

标签: pythontkinter

解决方案


使用exportselection=0Tkinter 列表框中的选项。

self.Lb1 = Listbox(self.left, selectmode=SINGLE, yscrollcommand=self.yscroll.set, font=50, bd=2, exportselection=0)
self.Lb2 = Listbox(self.left, selectmode=SINGLE, bd=2, exportselection=0)

如何在 tkinter 列表框中突出显示选择?


推荐阅读