Python Tkinter Listbox – How to Use

In this Python tutorial, we will learn about Python Tkinter Listbox with a few examples and also we will cover these topics

  • Introduction to Python Tkinter Listbox
  • How to get selected item from Python Tkinter Listbox
  • How to use curselection in Python Tkinter Listbox
  • How to get all items from the Python Tkinter Listbox
  • Python Tkinter Listbox with checkboxes
  • How to implement Python Tkinter Listbox scrollbar
  • Python Tkinter Listbox size
  • How to select multiple items from Python Tkinter Listbox?
  • Python Tkinter Listbox set selected item
  • Python Tkinter Listbox bind

If you are new to Python Tkinter or Python GUI programming, the check out Python GUI Programming (Python Tkinter).

Python Tkinter Listbox

  • Python Tkinter Listbox is another widget to display more than one item.
  • Users can either select a single item or multiple items.
  • Any item that is selected can be referred to as ‘ANCHOR‘. Here is the preview of the Python Tkinter Listbox.
python tkinter listbox
Python Tkinter Listbox

Syntax:

variable_name = Listbox(ws)
variable_name.pack()

# to insert items in the list
variable_name.insert(index, string)
python tkinter listbox syntax
Python Tkinter Listbox Syntax

Read: Python TKinter Add image.

Python tkinter listbox get selected item

  • Let us see how to get the selected item from the Python Tkinter Listbox. The get function is used to get the name of the selected item.
  • The selected item can be related to ANCHOR as the selected item acts as a hyperlink
  • We need to pass the ANCHOR as a parameter for the get function.

Code:

In this code, we have created a list, and the item of Listbox can be fetched by clicking on the button.

from tkinter import *

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x300')
ws.config(bg='#446644')

def showSelected():
    show.config(text=lb.get(ANCHOR))


lb = Listbox(ws)
lb.pack()
lb.insert(0, 'red')
lb.insert(1, 'green')
lb.insert(2, 'yellow')
lb.insert(3, 'blue')

Button(ws, text='Show Selected', command=showSelected).pack(pady=20)
show = Label(ws)
show.pack()

ws.mainloop()

Output:

In this output, there are four options available. User can click on any of the item and then click on the button to print the selected item.

python tkinter listbox show selected item
Python tkinter listbox get selected item

Read: How to Create a Snake Game in Python Tkinter

Python tkinter listbox curselection

  • Python tkinter Listbox curselection is used to display the selected item(s).
  • curselection is a predefined function that fetches the value(s) of a selected item or items.
  • curselection is mainly used when multiple values need to be fetched.

Code:

In this code, we have printed the selected item name when clicked on the button.

from tkinter import *

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x300')
ws.config(bg='#446644')

def showSelected():
    itm = lb.get(lb.curselection())
    var.set(itm)


var =StringVar()
lb = Listbox(ws)
lb.pack()

lb.insert(0, 'Iceland')
lb.insert(1, 'USA')
lb.insert(2, 'China')
lb.insert(3, 'Europe')

disp = Label(ws, textvariable=var)
disp.pack(pady=20)
Button(ws, text='Show Selected', command=showSelected).pack()

ws.mainloop()

Output:

In this output, we have displayed names of country. User will click on given country name and when clicked on button it will display the selected country name.

python tkinter listbox curSelection
Python tkinter listbox curselection

Read Python Tkinter Filter Function()

Python Tkinter Listbox get all items

  • Python Tkinter Listbox supports multiple selections of items. So in this section, we will learn to fetch all the selected items.

Code:

In this code, we have created a list of countries. Now user can select the countries he has visited so far, User can select multiple countries, and when he/she will click on the show selected button. Then selected countries name will be displayed.

from tkinter import *

ws = Tk() 
ws.title('Python Guides') 
ws.geometry('400x300')

var = StringVar()

def showSelected():
    countries = []
    cname = lb.curselection()
    for i in cname:
        op = lb.get(i)
        countries.append(op)
    for val in countries:
        print(val)

show = Label(ws, text = "Select Your Country", font = ("Times", 14), padx = 10, pady = 10)
show.pack() 
lb = Listbox(ws, selectmode = "multiple")
lb.pack(padx = 10, pady = 10, expand = YES, fill = "both") 

x =["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Australia", "Brazil", "Canada", "China", "Iceland", "Israel", "United States", "Zimbabwe"]

for item in range(len(x)): 
	lb.insert(END, x[item]) 
	lb.itemconfig(item, bg="#bdc1d6") 

Button(ws, text="Show Selected", command=showSelected).pack()
ws.mainloop() 

Output:

In this output, three countries are selected and same three countries are displayed below when showSelected button is clicked.

python tkinter listbox multiple selection
Python Tkinter Listbox get all items

Read Python Tkinter add function with examples

Python Tkinter Listbox with checkboxes

  • There s no way to put in the checkboxes inside the Listbox.
  • There use to be tixchecklist widget using which checkbox can be created inside the Listbox.
  • But tixchecklist was discontinued after python 3.6.

Python tkinter listbox scrollbar

Let us check how to implement scrollbar in Python Tkinter Listbox.

  • Scrollbars are used when content to be displayed is more than a dedicated area.
  • It facilitates to put in a large amount of data on the screen.
  • This data can be accessed by scrolling the scrollbar.
  • The scrollbar can be vertical or horizontal.
  • To implement a scrollbar in Python Tkinter Listbox there are mainly 3 steps:
    • create a scrollbar and put it in a parent or frame window
    • set the type of scrollbar: Horizontal or Vertical.
    • configure the scrollbar.
  • We will see this in detail in the below example.

Code:

In this code, both vertical & horizontal scrollbars are projected.
Vertical Scrollbar Source Code

from tkinter import *

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x300')
ws.config(bg='#446644')

def showSelected():
    show.config(text=lb.get(ANCHOR))

frame = Frame(ws)
frame.pack()

lb = Listbox(frame)
lb.pack(side=LEFT)

sb = Scrollbar(frame, orient=VERTICAL)
sb.pack(side=RIGHT, fill=Y)

lb.configure(yscrollcommand=sb.set)
sb.config(command=lb.yview)
lb.insert(0, 'red')
lb.insert(1, 'green')
lb.insert(2, 'yellow')
lb.insert(3, 'blue')
lb.insert(0, 'red')
lb.insert(1, 'green')
lb.insert(2, 'yellow')
lb.insert(3, 'blue')
lb.insert(0, 'red')
lb.insert(1, 'green')
lb.insert(2, 'yellow')
lb.insert(3, 'blue')
lb.insert(0, 'red')
lb.insert(1, 'green')
lb.insert(2, 'yellow')
lb.insert(3, 'blue')


Button(ws, text='Show Selected', command=showSelected).pack(pady=20)
show = Label(ws)
show.pack()

ws.mainloop()

Horizontal Scrollbar Source Code

from tkinter import *

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x300')
ws.config(bg='#446644')

def showSelected():
    show.config(text=lb.get(ANCHOR))

frame = Frame(ws)
frame.pack()

lb = Listbox(frame)
lb.pack()

sb = Scrollbar(frame, orient=HORIZONTAL)
sb.pack(fill=X)

lb.configure(xscrollcommand=sb.set)
sb.config(command=lb.xview)

lb.insert(0, 'Not all heros wear capes.')
lb.insert(1, 'Game changers are in blue')
lb.insert(2, 'With great power comes great responsibility')
lb.insert(3, 'A noun phrase has a noun or pronoun as the main word')



Button(ws, text='Show Selected', command=showSelected).pack(pady=20)
show = Label(ws)
show.pack()

ws.mainloop()

Output:

In these outputs, first image is of vertical scrollbar & second one is for horizontal scrollbar.

Vertical Scrollbar Output

python tkinter listbox vertical scrollbar
Python tkinter listbox scrollbar

Horizontal Scrollbar Output

python tkinter listbox horizontal scrollbar
Python tkinter listbox scrollbar

Read Python DataFrame to CSV

Python Tkinter Listbox size

  • You might be thinking that size is related to changing the size of Listbox.
  • But here size is a method in Listbox.
  • Size is used to get the number of lines in a Listbox.

Code:

In this code, we have created a program in of listbox having 4 items. We have used Size method to calculate the number of lines.

from tkinter import *

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x300')
ws.config(bg='#446644')

def showSelected():
    show.config(text=lb.get(ANCHOR))

lb = Listbox(ws)
lb.pack()

lb.insert(0, 'red')
lb.insert(1, 'green')
lb.insert(2, 'yellow')
lb.insert(3, 'blue')

print(lb.size())

Button(ws, text='Show Selected', command=showSelected).pack(pady=20)
show = Label(ws)
show.pack()

ws.mainloop()

Output:

In this output, implementation of size method is projected. Seize method is use to calculate the lines in Listbox. So in this case, there were 4 items in 4 lines. So the output appeared is 4.

python tkinter listbox size
Python tkinter listbox size

Python Tkinter Listbox multiple selection

  • Multiple selections refer to fetching all items from the Python Tkinter Listbox.
  • Listbox supports multiple selections of items.
  • selectmode = ‘multiple’ is used to select multiple items.

Code:

from tkinter import *

ws = Tk() 
ws.title('Python Guides') 
ws.geometry('400x300')

var = StringVar()

def showSelected():
    countries = []
    cname = lb.curselection()
    for i in cname:
        op = lb.get(i)
        countries.append(op)
    for val in countries:
        print(val)

show = Label(ws, text = "Select Your Country", font = ("Times", 14), padx = 10, pady = 10)
show.pack() 
lb = Listbox(ws, selectmode = "multiple")
lb.pack(padx = 10, pady = 10, expand = YES, fill = "both") 

x =["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Australia", "Brazil", "Canada", "China", "Iceland", "Israel", "United States", "Zimbabwe"]

for item in range(len(x)): 
	lb.insert(END, x[item]) 
	lb.itemconfig(item, bg="#bdc1d6") 

Button(ws, text="Show Selected", command=showSelected).pack()
ws.mainloop() 

Output:

python tkinter listbox multiple selection
Python tkinter listbox multiple selection

Python Tkinter Listbox set selected item

  • Python set selected item refers to setting the default item in the Python Tkinter Listbox.
  • Every time when the user runs the program a default value is already selected

Code:

In this code, ‘Yellow’, that is on index 2 is selected as a default selection. Changing the index number in select_set will change the default item preference.

from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x300')
ws.config(bg='#446644')

def showSelected():
    show.config(text=lb.get(ANCHOR))
    

lb = Listbox(ws)
lb.pack()

lb.insert(0, 'red')
lb.insert(1, 'green')
lb.insert(2, 'yellow')
lb.insert(3, 'blue')
lb.select_set(2) 

Button(ws, text='Show Selected', command=showSelected).pack(pady=20)
show = Label(ws)
show.pack()

ws.mainloop()

Output:

In this output, yellow is selected by-default immediately after running the program.

python tkinter listbox set selected
Python tkinter listbox set selected item

Python Tkinter Listbox bind

  • Python Listbox bind is used to set an action that will occur when the event is performed.
  • Any activity that happened on the Listbox widget is called an event.
  • focus-gained, focus-lost, clicked, etc are a few examples of events.
  • In this section, we will learn about a few popular bind events:
    • <<ListboxSelect>> : It tells about when user selected or deselected Listbox item(s)
    • <Double-1>: It triggers activity when the user double clicks on an item(s) in a Listbox.

Code:

In this code, <<ListboxSelect>> is used to bind the event with callback function. This code returns the index number of the selected Listbox item(s).

from tkinter import *

def showSelected(event):
    temp= str(event) + '\n' + str(lb.curselection())
    show.configure(text=temp)

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x250')
ws.config(bg='#F9F833')

var = StringVar(value=dir())

lb = Listbox(ws, listvariable=var, selectmode='extended')
lb.pack()

lb.bind('<<ListboxSelect>>', showSelected)

show = Label(ws)
show.pack()

ws.mainloop()

Output:

In this output, below label shows the index number(s) of selected item(s) in Listbox.

python tkinter listbox bind
Python tkinter listbox bind

You may like the following Python tutorials:

In this tutorial we have learned about Python Tkinter listbox also we have covered these topics:

  • What is Python tkinter listbox and how to use it?
  • How to get the selected item from the python tkinter listbox?
  • Python tkinter listbox curselection
  • How to get all items from the Python tkinter Listbox?
  • Python tkinter listbox with checkboxes
  • Python tkinter listbox scrollbar
  • Python tkinter listbox size
  • Python tkinter listbox multiple selection
  • Python tkinter listbox set selected item
  • Python tkinter listbox bind