How to remove multiple selected items in listbox in Tkinter?
Last Updated :
08 Mar, 2024
Prerequisite: Tkinter, Listbox in Tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications.
In this article, we will learn how to remove multiple selected checkboxes in Listbox Using Tkinter in Python.
Let’s Understand step by step implementation:-
1. Create Normal Tkinter Window
Python3
from tkinter import *
root = Tk()
root.geometry( "200x200" )
root.mainloop()
|
Output:
2. Add Listbox using Listbox() method
Syntax:
Listbox(root, bg, fg, bd, height, width, font, ..)
Python3
from tkinter import *
root = Tk()
root.geometry( "200x200" )
listbox = Listbox(root, selectmode = MULTIPLE)
listbox.pack()
items = [ "Apple" , "Orange" , "Grapes" , "Banana" , "Mango" ]
for item in items:
listbox.insert(END, item)
Button(root, text = "delete" ).pack()
root.mainloop()
|
Output:
3. Remove Selected Item From Listbox
- Get a List of selected Items from Listbox using the curselection() method.
- Iterate through all list and remove item using delete() method
Below is the implementation:-
Python3
from tkinter import *
def remove_item():
selected_checkboxs = listbox.curselection()
for selected_checkbox in selected_checkboxs[:: - 1 ]:
listbox.delete(selected_checkbox)
root = Tk()
root.geometry( "200x200" )
listbox = Listbox(root, selectmode = MULTIPLE)
listbox.pack()
items = [ "Apple" , "Orange" , "Grapes" , "Banana" , "Mango" ]
for item in items:
listbox.insert(END, item)
Button(root, text = "delete" , command = remove_item).pack()
root.mainloop()
|
Output:
Share your thoughts in the comments
Please Login to comment...