Listbox:列表框用於顯示項目列表
語法:
lb=List(master,option,···)
參數 master:父窗口
option:常用的選項列表,可以有多個,用逗號隔開
這裏是做一個列表框,可以通過for循環向Listbox中插入項目列表和索引值向其中添加項目兩種方法。其中,點擊Button按鈕後,可以實現將Listbox中光標選中的項目顯示在標籤Label中。
代碼如下
import tkinter as tk
window=tk.Tk()
window.title('my window')
window.geometry('200x200')
var1=tk.StringVar()
l=tk.Label(window,bg='green',width=6,textvariable=var1)
l.pack() #不設置參數,默認居中
def print_selection():
value=lb.get(lb.curselection())
#通過curselection()即光標選定的元素,獲得Listbox中選定的項目
var1.set(value)
b1=tk.Button(window,text='print selection',width=15,height=1,command=print_selection)
b1.pack()
var2=tk.StringVar()
var2.set((55,22,11))
lb=tk.Listbox(window,listvariable=var2)
list_items=[1,2,3,4]
for item in list_items: #用for循環將定義的列表中的元素插入Listbox中
lb.insert('end',item)
lb.insert(1,'first') #用索引值進行插入,first將插入在Listbox第二位
lb.insert(2,'second')
lb.delete(2)
#用delete刪除Listbox中的元素,只要給一個索引值就可以,運行後second已經刪除不會被插入
lb.pack()
window.mainloop()
當光標選擇first時,點擊print selection按鈕,選中的項目將在label標籤上顯示出來,如下圖