Search code examples
pythontkinterlistboxanchor

Tkinter Listbox.get(ANCHOR) not grabbing correct item when arrow keys are used to scroll


Consider the below piece of Python code

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()
  • If I click the listbox item Indigo, then press the Show Selected button, text appears at the bottom that says Indigo. This is as intended

  • If I then click the item Yellow & press the button, the text updates from Indigo to Yellow

  • If I then click Red, then press the down arrow key (moving the blue highlight bar from Red to Orange), then press the button, the text updates to Red instead of Orange, as Red was the previously clicked item. It should instead update to Orange, as Orange is the currently selected item

After some searching, I've been unable to find a way to set the ANCHOR of a listbox without actually clicking it. If such a function exists (or doesn't exist, meaning that a workaround is needed), all help is appreciated. Thanks!


Solution

  • Using Box.get(ACTIVE) instead of Box.get(ANCHOR) solves this issue. Credit to acw1668 for this

    Also, as an extension of this, consider a version where instead of using the ShowButton widget to update the text, you use Box.bind("<<ListboxSelect>>", ShowSelected). Assuming you can only select one Listbox item at a time, Box.get(Box.curselection()) is the best solution, as Box.get(ACTIVE) will cause left-click selections to show the previously selected option instead of the currently selected option