首页 > 解决方案 > Tkinter- Listbox 选择当前突出显示项的倒数

问题描述

我正在尝试制作一个按钮,该按钮将自动选择与当前选择的内容相反的按钮。我没有尝试在下面的代码中创建此功能,但它不起作用。在我的代码中,我试图突出显示所有内容,然后取消选择最初选择的内容,这相当于获得相反的内容。有人可以看看我的代码,看看有什么问题吗?

from tkinter import *
from tkinter import ttk

main = Tk()
main.geometry("+50+150")
frame = ttk.Frame(main, padding=(3, 3, 12, 12))
frame.grid(column=0, row=0, sticky=(N, S, E, W))

lstbox = Listbox(frame, selectmode=MULTIPLE, width=20, height=10)
lstbox.grid(column=0, row=0, columnspan=2)

for i in range(10):
    lstbox.insert(0, i)

def select(evt):
    global selected
    global selection
    selection = lstbox.curselection()
    for i in selection:
        selected = lstbox.get(i)
        print(selected)

lstbox.bind('<<ListboxSelect>>', select)

def select_inverse():
    lstbox.selection_set(0, END)
    lstbox.selection_clear(selected, selected)

btn = ttk.Button(frame, text="Inverse", command=select_inverse)
btn.grid(column=1, row=1)

main.mainloop()

标签: pythontkinter

解决方案


您快到了,但您不需要列表框项目的实际值。您只能使用索引进行操作。

此外,您不需要(至少对于此特定任务不需要)select绑定到lstbox. 可以直接在select_inverse.

def select_inverse():
    selection = lstbox.curselection()
    lstbox.selection_set(0, END) 
    for item in selection:
        lstbox.selection_clear(item)

推荐阅读