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

Tkinter Listbox.get(ANCHOR)使用箭头键滚动时无法获取正确项

Tkinter Listbox:方向键切换选中项后获取内容异常的解决方法

问题重现代码

from tkinter import *

root = Tk()
root.title("Listbox Test")
root.geometry("200x300")

def ShowSelected():
    ShowText.config(text = Box.get(ANCHOR))

Box = Listbox(root)
Box.pack()
Box.insert(0, "red", "orange", "yellow", "green", "blue", "indigo", "violet")

ShowButton = Button(root, text="Show Selected", command = ShowSelected)
ShowButton.pack(pady=20)
ShowText = Label(root)
ShowText.pack()

root.mainloop()

问题现象

  • 点击列表框中的Indigo项,再点击Show Selected按钮,底部显示Indigo,符合预期
  • 接着点击Yellow项并按下按钮,文本从Indigo更新为Yellow
  • 再点击Red项,按下向下箭头键(将蓝色高亮条从Red移至Orange),此时按下按钮,文本却更新为Red而非当前选中的Orange——原因是Red是之前点击设置的锚点项,方向键移动选中高亮条不会自动更新ANCHOR

解决方案

方案1:改用curselection()获取当前选中项

curselection()会返回当前高亮选中项的索引列表(即使是通过方向键切换的),无需依赖锚点项。修改ShowSelected函数即可:

def ShowSelected():
    selected = Box.curselection()
    if selected:  # 确保有选中项
        ShowText.config(text = Box.get(selected[0]))

方案2:绑定方向键事件自动更新ANCHOR

如果需要保留使用ANCHOR的逻辑,可以绑定上下方向键事件,在按键触发时将锚点同步到当前选中项:

from tkinter import *

root = Tk()
root.title("Listbox Test")
root.geometry("200x300")

def ShowSelected():
    ShowText.config(text = Box.get(ANCHOR))

def update_anchor(event):
    selected = Box.curselection()
    if selected:
        Box.anchor_set(selected[0])

Box = Listbox(root)
Box.pack()
Box.insert(0, "red", "orange", "yellow", "green", "blue", "indigo", "violet")
# 绑定上下方向键事件
Box.bind("<Up>", update_anchor)
Box.bind("<Down>", update_anchor)

ShowButton = Button(root, text="Show Selected", command = ShowSelected)
ShowButton.pack(pady=20)
ShowText = Label(root)
ShowText.pack()

root.mainloop()

内容的提问来源于stack exchange,提问作者Theodore Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:01:09