python - 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()
解决方案
您快到了,但您不需要列表框项目的实际值。您只能使用索引进行操作。
此外,您不需要(至少对于此特定任务不需要)select
绑定到lstbox
. 可以直接在select_inverse
.
def select_inverse():
selection = lstbox.curselection()
lstbox.selection_set(0, END)
for item in selection:
lstbox.selection_clear(item)
推荐阅读
- java - 运算符 switchMap() 不会取消订阅上一个请求
- c++ - 如何从用户输入中替换代码中的变量值?
- php - php验证散列密码在我的函数中不起作用
- android - 如何将 Piniew OTP 字段设计从方框更改为简单线?
- ios - 动态改变 cell.update 日期函数?
- mysql - MySQL Server 基于线程而不是基于进程是什么意思?
- spring - Junit 用一堆@Pointcut 测试一个类
- django - 如何修复在 EC2 上运行的 Django 实例中更高的内存利用率,是否由于 gunicorn.sock 的多个运行进程?
- html - 如何在背景颜色之上设置背景图像
- algorithm - 这个迷宫生成算法叫什么名字?