Tkinter ListBox Add and Delete Item
This section will illustrate the application of adding and removing Listbox items with a more practical example.
Example#1
Add and delete items. The program has 4 widget controls, Entry is an input control where you can enter items, click "Add" button after entering items, the items in Entry will be added to the Listbox, and Entry will be emptied. If you select the items in the Listbox and then click the "Delete" button, you can delete the selected items.
from tkinter import *
def itemAdded():
varAdd = entry.get()
if (len(varAdd.strip()) == 0):
return
lb.insert(END,varAdd)
entry.delete(0,END)
def itemDeleted():
index = lb.curselection()
if (len(index)==0):
return
lb.delete(index)
root = Tk()
root.title("apidemos.com")
# root.geometry("300x250")
entry = Entry(root)
entry.grid(row=0,column=0,padx=5,pady=5)
# Create "Add" Button
btnAdd = Button(root,text="Add",width=10,command=itemAdded)
btnAdd.grid(row=0,column=1,padx=5,pady=5)
# Create Listbox
lb = Listbox(root)
lb.grid(row=1,column=0,columnspan=2,padx=5,sticky=W)
# Create Delete Button
btnDel = Button(root,text="Delete",width=10,command=itemDeleted)
btnDel.grid(row=2,column=0,padx=5,pady=5,sticky=W)
root.mainloop()
Output:
The following are the operations for adding items and deleting items.