In python you can use the following method to get the selected element in lisxtbox component.
A listbox shows a list of options. You can then click on any of those options. By default it won’t do anything, but you can link that to a callback function or link a button click.
Output:

python listbox element click
Example 1: Tkinter listbox select event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# -*- coding: utf-8 -*- import tkinter as tk def getElement(event): selection = event.widget.curselection() index = selection[0] value = event.widget.get(index) result.set(value) print(index,' -> ',value) root = tk.Tk() root.title("Code4Example.com") # Add a title result =tk.StringVar() tk.Label(root,text="""Click Listbox Element""").grid(row = 0, column = 0) tk.Label(root,text="""result""", textvariable=result).grid(row = 1, column = 0) var2 = tk.StringVar() var2.set(('Apple','Banana','Pear', 'Peach')) lb = tk.Listbox(root, listvariable=var2) lb.grid(row = 0, column = 1) lb.bind('<<ListboxSelect>>', getElement) #Select click root.mainloop() |
Example 2:Select listbox element by double click
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# -*- coding: utf-8 -*- import tkinter as tk def getElement(event): selection = event.widget.curselection() index = selection[0] value = event.widget.get(index) result.set(value) print(index,' -> ',value) root = tk.Tk() root.title("Code4Example.com") # Add a title result =tk.StringVar() tk.Label(root,text="""Click Listbox Element""").grid(row = 0, column = 0) tk.Label(root,text="""result""", textvariable=result).grid(row = 1, column = 0) var2 = tk.StringVar() var2.set(('Apple','Banana','Pear', 'Peach')) lb = tk.Listbox(root, listvariable=var2) lb.grid(row = 0, column = 1) lb.bind('<Double-1>', getElement) #double click root.mainloop() |
Python Tkinter listbox get selected item
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
.... .... def getElement(event): selection = event.widget.curselection() index = selection[0] value = event.widget.get(index) print(index,' -> ',value) .... .... lb = tk.Listbox(root, listvariable=var2) lb.grid(row = 0, column = 1) lb.bind('<<ListboxSelect>>', getElement) #Select click |