You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter Listbox绑定Button-1事件获取选中项滞后问题问询

问题原因

你绑定的<Button-1>事件回调执行优先级高于Listbox内置的选中状态更新逻辑:点击条目时会先执行你定义的回调函数,此时Listbox还未将当前点击的条目标记为选中状态,因此curselection()只能拿到点击前的选中结果——首次点击前无选中项就返回空元组,后续点击返回上一次的选中值。

解决方法

方法1:使用Listbox专属选中事件(最推荐)

直接绑定<<ListboxSelect>>虚拟事件,该事件会在Listbox选中状态更新完成后触发,可直接拿到最新的选中结果,修改后的代码如下:

from tkinter import *
root = Tk()
root.title("test listbox")

list_box = Listbox(root)
list_box.pack()
for i in range(0,10):
    list_box.insert("end",i)

def def_fun(event):
    print(list_box.curselection())
# 仅需要修改绑定的事件即可
list_box.bind("<<ListboxSelect>>",def_fun)
root.mainloop()

方法2:保留绑定,通过点击坐标直接获取条目

如果必须使用<Button-1>事件,可以不依赖curselection(),直接通过点击事件的坐标计算对应条目索引:

def def_fun(event):
    # 获取点击位置最近的条目索引
    current_index = event.widget.nearest(event.y)
    print(current_index)
    # 如果需要获取条目内容可以调用 list_box.get(current_index)
list_box.bind("<Button-1>",def_fun)

内容的提问来源于stack exchange,提问作者Siddhant Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:15:03