What is the difference between activated element and selected element?

Viewed 38

This question is about listbox.I'm not sure what's the difference between activated element and selected element.What is the point?When I select an item (with an arrow key or mouse) in a listbox,the item is both selected and activated,Which make me also question what's the point with the two seperated methods: active(index) method and selection_set(index) method? One more question:When is active without selected,and the opposite?

2 Answers

Several elements in a listbox can be selected, but only one of them can be active. The active element can deal with inputs, whether they are selected just says something about their internal state.

A listbox with selectmode "multiple" or "extended" can have any number of "selected" items, and at most one "active" item. Most keyboard bindings operate on the "active" item. For instance, the up and down arrow keys change the "active" item, and the spacebar toggles whether the active item is selected or not.

With selectmode "browse" (the default), the active item is always the (sole) selected item, and since listboxes don't acquire the keyboard focus by default, you won't see a location cursor unless you traverse to the listbox with . So the "active" item frequently isn't visually distinguishable.

The distinction is easiest to see with a listbox that has keyboard focus and selectmode multiple.

Example to distinguish both:

from tkinter import *

# Create the root window
root = Tk()
root.geometry('180x200')

# Create a listbox
listbox = Listbox(root, width=40, height=10, selectmode=MULTIPLE)

# Inserting the listbox items
listbox.insert(1, "Topic A")
listbox.insert(2, "Topic B")
listbox.insert(3, "Topic C")
listbox.insert(4, "Topic D")
listbox.insert(5, "Topic E")


# Function for printing the
# selected listbox value(s)
def selected_item():
    print("Selected")
    for i in listbox.curselection():
        print(listbox.get(i))
    print("")

# active listbox value
def active_item():
    print("Active")
    print(listbox.get(ACTIVE))
    print("")


btn = Button(root, text='Print Selected', command=selected_item)
btn2 = Button(root, text="Print Active", command=active_item)

# Placing the button and listbox
btn.pack(side='bottom')
btn2.pack(side='bottom')
listbox.pack()

root.mainloop()
Related