Tkinter Listbox Order Items
When using Listbox, you often need to handle the sorting of items, which is explained in the following example.
Example#1
This program click the "Sort" button when the default is to sort from small to large, if the check box and then click the "Sort" button will be sorted from large to small.
from tkinter import *
def itemsSorted():
if (var.get() == True):
revBool = True
else:
revBool = False
listTmp = list(lb.get(0,END))
sortedList = sorted(listTmp,reverse=revBool)
lb.delete(0,END)
for item in sortedList:
lb.insert(END,item)
fruits = [
"Banana","Watermelon","Pineapple",
"Orange","Grapes","Mango"
]
root = Tk()
root.title("apidemos.com")
# root.geometry("300x250")
lb = Listbox(root)
for fruit in fruits:
lb.insert(END,fruit)
lb.pack(padx=10,pady=5)
# Create "Order" Button
btn = Button(root,text="Order",command=itemsSorted)
btn.pack(side=LEFT,padx=10,pady=5)
# Create Sorting Settings checkbox
var = BooleanVar()
cb = Checkbutton(root,text="Sorted from largest to smallest",variable=var)
cb.pack(side=LEFT)
root.mainloop()
Output:
Here is the interface of using the default sorting and using the "big to small" sorting.