How to keep selections highlighted in a Tkinter Listbox?

In Tkinter applications, you might need to keep selections highlighted in a Listbox while users interact with other widgets. By default, when you click on another widget, the Listbox loses its selection highlighting. The exportselection property solves this problem by controlling whether the selection should remain visible.

Understanding exportselection

The exportselection parameter determines whether the Listbox selection should be exported to the system's selection mechanism. When set to False, selections remain highlighted even when focus moves to other widgets.

Syntax

Listbox(parent, exportselection=False)

Example: Multiple Listboxes with Persistent Selections

Here's how to create two Listboxes where selections remain highlighted ?

import tkinter as tk

# Create main window
win = tk.Tk()
win.geometry("750x350")
win.title("Persistent Listbox Selections")

# Create first listbox with exportselection=False
listbox_a = tk.Listbox(win, exportselection=False)
listbox_a.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

# Create second listbox with exportselection=False
listbox_b = tk.Listbox(win, exportselection=False)
listbox_b.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

# Add items to first listbox
programming_languages = ["Python", "Java", "C++", "Rust", "GoLang"]
for i, language in enumerate(programming_languages):
    listbox_a.insert(i, language)

# Add items to second listbox
web_languages = ["C#", "JavaScript", "R", "PHP", "TypeScript"]
for i, language in enumerate(web_languages):
    listbox_b.insert(i, language)

# Function to show selected items
def show_selections():
    selection_a = [listbox_a.get(i) for i in listbox_a.curselection()]
    selection_b = [listbox_b.get(i) for i in listbox_b.curselection()]
    print(f"Listbox A selections: {selection_a}")
    print(f"Listbox B selections: {selection_b}")

# Add button to demonstrate persistent selections
button = tk.Button(win, text="Show Selections", command=show_selections)
button.pack(pady=5)

win.mainloop()

Comparison of exportselection Values

exportselection Value Selection Behavior Use Case
True (default) Selection disappears when focus moves Single listbox applications
False Selection remains highlighted Multiple listboxes or complex UIs

Practical Use Cases

Setting exportselection=False is particularly useful when ?

  • File management applications: Selecting files from multiple directories
  • Data comparison tools: Comparing items between different lists
  • Multi?step workflows: Maintaining context across different UI elements

Conclusion

Use exportselection=False to keep Listbox selections highlighted when users interact with other widgets. This creates a better user experience for applications requiring multiple or persistent selections.

Updated on: 2026-03-25T19:32:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements