Skip to content
Related Articles
Open in App
Not now

Related Articles

How to get selected value from listbox in tkinter?

Improve Article
Save Article
  • Last Updated : 10 Jun, 2021
Improve Article
Save Article

Prerequisites: Tkinter, Listbox

ListBox is one of the many useful widgets provided by Tkinter for GUI development. The Listbox widget is used to display a list of items from which a user can select one or more items according to the constraints. In this article, we’ll see how we can get the selected value(s) from a Listbox widget.

Code:

Python3




# Python3 program to get selected
# value(s) from tkinter listbox
 
# Import tkinter
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, "Data Structure")
listbox.insert(2, "Algorithm")
listbox.insert(3, "Data Science")
listbox.insert(4, "Machine Learning")
listbox.insert(5, "Blockchain")
 
# Function for printing the
# selected listbox value(s)
def selected_item():
     
    # Traverse the tuple returned by
    # curselection method and print
    # corresponding value(s) in the listbox
    for i in listbox.curselection():
        print(listbox.get(i))
 
# Create a button widget and
# map the command parameter to
# selected_item function
btn = Button(root, text='Print Selected', command=selected_item)
 
# Placing the button and listbox
btn.pack(side='bottom')
listbox.pack()
 
root.mainloop()

 

 

Output:

 

GUI window with output

 

Explanation: 

 

The curselection method on listbox returns a tuple containing the indices/line numbers of the selected item(s) of the listbox, starting from 0. The selected_item function that we made, traverses the tuple returned by the curselection method and prints the corresponding item of the listbox using the indices. It is executed when we press the “Print Selected” button.  In the case of no selected items, curselection method returns an empty tuple.

 

Note: You can change the selectmode parameter of the listbox widget to “SINGLE” for putting a constraint of choosing a single value only.

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!