Tkinter Listbox
Show a List
A Listbox shows a list of items. Use insert() to add the items:
Example
A list of fruits:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
listbox = tk.Listbox(window)
listbox.pack()
listbox.insert(tk.END, "Apple")
listbox.insert(tk.END, "Banana")
listbox.insert(tk.END, "Cherry")
window.mainloop()
Result:
tk.END means "at the end", so each item is added after the items that are already in the list.
Get the Selected Item
The user selects an item by clicking on it. Use curselection() to find out which item is selected:
Example
Show the selected fruit:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
fruits = ["Apple", "Banana", "Cherry"]
def show():
selected = listbox.curselection()
if selected:
choice = listbox.get(selected[0])
label.config(text=choice)
listbox = tk.Listbox(window, height=4)
listbox.pack()
for fruit in fruits:
listbox.insert(tk.END, fruit)
button = tk.Button(window, text="Show",
command=show)
button.pack()
label = tk.Label(window)
label.pack()
window.mainloop()
Result:
After selecting Banana and clicking Show:
curselection() returns a tuple with the index of the selected item, like (1,).
It is empty if nothing is selected, so the if statement checks that first.
listbox.get(index) returns the text of the item at that index. The first item has index 0.
height=4 makes the list box 4 lines high, and the for loop adds one item for each fruit in the list.
Delete an Item
Use delete() with an index to remove an item:
Example
Delete the selected fruit:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
fruits = ["Apple", "Banana", "Cherry"]
def delete():
selected = listbox.curselection()
if selected:
listbox.delete(selected[0])
listbox = tk.Listbox(window, height=4)
listbox.pack()
for fruit in fruits:
listbox.insert(tk.END, fruit)
button = tk.Button(window, text="Delete",
command=delete)
button.pack()
window.mainloop()
Result:
After selecting Banana and clicking Delete:
In the Tkinter To-Do List chapter, you will use a Listbox to build a small app.