今天延續昨天的Listbox做一些更進階的操作,加入刪除、項目的排序和拖曳項目,這些都是平常常會用到的。
♠♣今天的文章大綱♥♦
用Entry輸入內容,案加入按鈕後便會加入Listbox,案刪除後就會刪除。
import tkinter as tk
root = tk.Tk()
root.title('cuteluluWindow')
root.configure(bg="#7AFEC6")
root.iconbitmap('heart_green.ico')
root.geometry('300x300')
def Added():
g = entry.get()
if (len(g.strip()) ==0):
return
lb.insert ('end', g)
entry.delete(0, 'end')
def Deleted():
index = lb.curselection ()
if (len (index) == 0):
return
lb.delete(index)
entry = tk.Entry(root)
entry.grid(row=0, column=0, padx=5, pady=5)
bAdd = tk.Button (root, text="Add",width=10, command=Added)
bAdd.grid(row=0, column=1, padx=5, pady=5)
lb = tk.Listbox (root)
lb.grid(row=1,column=0,columnspan=2,padx=5,sticky='w')
bDel = tk.Button(root,text="Delete",width=10,command=Deleted)
bDel.grid(row=2,column=0,padx=5,pady=5 ,sticky='w')
root.mainloop()
執行結果⬇⬇⬇
按Add鍵
加入項目
選取項目
按Delete鍵
設定要從小到大排或是從大到小排列,執行後可以從選相框去做選擇。
import tkinter as tk
root = tk.Tk()
root.title('cuteluluWindow')
root.configure(bg="#7AFEC6")
root.iconbitmap('heart_green.ico')
root.geometry('300x300')
def choise():
if (var.get() == True):
revBool=True #小到大排序
else:
revBool=False #大到小排序
listTmp=list (lb.get (0,'end'))
sl= sorted(listTmp,reverse=revBool)
lb.delete(0, 'end')
for item in sl:
lb.insert ('end', item)
singers =["Sam Smith", "Of Monsters and Men", "The Cure", "Bruno Mars", "Taylor Swift", "John Legend"]
lb= tk.Listbox (root)
for singer in singers:
lb.insert ('end', singer)
lb.pack(padx=10, pady = 5)
b = tk.Button(root, text="Sort", command=choise)
b.pack(side = 'left', padx = 10, pady = 5)
var = tk.BooleanVar()
cb = tk.Checkbutton (root, text="小到大", variable=var)
cb.pack(side='left')
root.mainloop()
執行結果⬇⬇⬇
一開始
大到小
小到大
可以將選項拖曳換位置。
import tkinter as tk
root = tk.Tk()
root.title('cuteluluWindow')
root.configure(bg="#7AFEC6")
root.iconbitmap('heart_green.ico')
root.geometry('300x300')
def get(event):
lb.index = lb.nearest(event.y)
def choise(event):
newIndex = lb.nearest(event.y)
if newIndex < lb.index:
x=lb.get (newIndex)
lb.delete(newIndex)
lb.insert(newIndex+1,x)
lb.index = newIndex
elif newIndex > lb.index:
x = lb.get(newIndex)
lb.delete(newIndex)
lb.insert(newIndex-1,x)
lb.index= newIndex
singers =["Sam Smith", "Of Monsters and Men", "The Cure", "Bruno Mars", "Taylor Swift", "John Legend"]
lb = tk.Listbox(root)
for singer in singers:
lb.insert ('end', singer)
lb.bind("<Button-1>",get)
lb.bind("<B1-Motion>", choise)
lb.pack(padx = 1 , pady=10)
root.mainloop()
執行結果⬇⬇⬇
點選一個選項
將其拖曳至想要的位置
Listbox就到今天了,明天會開始講OptionMenu7部分囉~~~