十二、列表框List與滾動條Scroller

建立列表框

它的使用格式如下。

Listbox(父對象,options,···)

List()方法的第一個參數(shù)是父對象,表示這個列表框?qū)⒔⒃谀囊粋€父對象內(nèi)。下列是Listbox()方法
內(nèi)其他常用的options參數(shù)。
(1)bg或background:背景色彩。
(2)borderwidth或bd:邊界寬度,默認是兩個像素。
(3)cursor:當(dāng)鼠標光標在列表框上時的光標形狀。
(4)fg或froeground:字形色彩。
(5)font:字形。
(6)height:高,單位是字符,默認是10。
(7)highlightcolor:當(dāng)列表框獲得焦點時的顏色。
(8)highlightthickness:當(dāng)列表框獲得焦點時的厚度。
(9)listvariable:以變量方式處理選項內(nèi)容。
(10)relief:默認是relief=FLAT,可由此控制列表框外框,默認是SUNKEN。
(11)selectbackground:被選取字符串的背景色彩。
(12)selectmode:可以決定由多少選項被選,以及鼠標拖拽如何影響選項。
1.BROWSE:這是默認值,我們可以選擇一個選項,如果選取一個選項同時拖拽鼠標,將造成選項
最后的位置是被選取的項目位置。
2.SINGLE:只能選擇一個選項,可以用單擊方式選取,不可用拖拽方式更改所選的項目。
3.MULTIPLE:可以選擇多個選項,單擊項目可以切換是否選擇該項目。
4.EXTENDED:單擊第一個項目然后拖拽到最后一個項目,即可選擇這個區(qū)間的一些列選項。單擊
可以選擇第一個項目,此時若是按住Shift鍵并單擊另一個項目,可以選取區(qū)間項目。
(13)width:寬,單位是字符。
(14)xscrollcommand:在x軸使用滾動條。
(15)yscrollcommand:在y軸使用滾動條。

樣例:建立列表框1,然后使用字符高度5建立列表框2。

from tkinter import *

root=Tk()
root.title("ch12_1")
root.geometry("300x210")

lb1=Listbox(root)
lb1.pack(side=LEFT,padx=5,pady=10)
lb2=Listbox(root,height=5,relief="raised")
lb2.pack(anchor=N,side=LEFT,padx=5,pady=10)

root.mainloop()
image.png

建立列表框項目insert()

可以使用insert()方法為列表框建立項目,這個方法的使用格式如下。
insert(index,elements)

上述index是項目插入位置,如果是插在最后面可以使用END。

樣例:建立列表框,同時為這個列表框建立Banana、Watermelon、Pineapple三個項目。

from tkinter import *

root=Tk()
root.title("ch12_2")
root.geometry("300x210")

lb=Listbox(root)
lb.insert(END,"Banana")
lb.insert(END,"Watermelon")
lb.insert(END,"Pineapple")
lb.pack(pady=10)

root.mainloop()
image.png

如果所要建立的項目很多時,建議使用list方式先儲存項目,然后使用for···in循環(huán)方式將list
內(nèi)的列表項目插入到列表框。

樣例2:使用Listbox()構(gòu)造方法時增加selectmode=MULTIPLE參數(shù)設(shè)置,這個設(shè)置可以讓
用戶選取多個項目。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_3")
root.geometry("300x210")

lb=Listbox(root,selectmode=MULTIPLE)
for fruit in fruits:
    lb.insert(END,fruit)

lb.pack(pady=10)

root.mainloop()
image.png

如果使用selectmode=EXTENDED參數(shù),此時可以使用拖拽的方式選擇區(qū)間項目。如果先單擊
一個項目,然后按住Shift鍵并單擊另一個項目可以選取這個區(qū)間內(nèi)的項目。

目前插入選項皆是插在最后面,所以語法是insert(END,elements),其實第一個參數(shù)是索引值,
如果將END改為ACTIVE,表示是在目前選項前面加入一個項目,如果尚未選擇則此ACTIVE是0。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple"]

root=Tk()
root.title("ch12_3")
root.geometry("300x210")

lb=Listbox(root,selectmode=EXTENDED)
for fruit in fruits:
    lb.insert(END,fruit)
lb.insert(ACTIVE,"Orange","Grapes","Mango")
lb.pack(pady=10)

root.mainloop()
image.png

Listbox的基本操作

Listbox的基本操作

本節(jié)將介紹下列常用的Listbox控件操作的方法。
(1)size():傳回列表項目的數(shù)目。
(2)select_set():選取特定索引項。
(3)delete():刪除特定索引項。
(4)get():傳回指定索引項。
(5)curselection():傳回選取項目的索引。
(6)selection_include():檢查指定索引是否被選取。

列出列表框的選項數(shù)量size()

這個方法可以列出選項數(shù)目。

樣例:建立列表框,然后列出列表框中的項目數(shù)量。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_7")
root.geometry("300x210")

lb=Listbox(root,selectmode=EXTENDED)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=10)
print("items數(shù)字:",lb.size())

root.mainloop()
image.png

選取特定索引項selection_set()

如果selection_set方法內(nèi)含一個參數(shù),表示選取這個索引項,這個功能常被用于建立好
Listbox后,設(shè)定初次選擇的項目。

樣例:建立一個Listbox,然后設(shè)定初次的選擇項目是索引為0的項目。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_8")
root.geometry("300x210")

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=10)
lb.selection_set(0)
root.mainloop()
image.png

如果在selection_set()方法內(nèi)有兩個參數(shù)時,則表示選取區(qū)間選項,第一個參數(shù)是區(qū)間的起始
索引項,第二個參數(shù)是區(qū)間的結(jié)束索引項。

樣例二,建立一個Listbox,然后設(shè)定初次的選擇項目是索引為0~3的項目。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_8")
root.geometry("300x210")

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=10)
lb.selection_set(0,3)
root.mainloop()
image.png

刪除特定索引項delete()

如果delete()方法內(nèi)含有一個參數(shù),表示刪除這個索引項。

樣例:建立Listbox后刪除索引為1的項目,原先索引為1的項目是Watermelon,經(jīng)
執(zhí)行后將沒有顯示,因為已經(jīng)被刪除了。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_10")
root.geometry("300x210")

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=10)
lb.delete(1)

root.mainloop()

如果在delete()方法內(nèi)有兩個參數(shù)時,則表示刪除區(qū)間選項,第一個參數(shù)是區(qū)間的起始索引項,
第二個參數(shù)是區(qū)間的結(jié)束索引項。

樣例2:建立一個Listbox,然后刪除索引為1~3的項目。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_10")
root.geometry("300x210")

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=10)
lb.delete(1,3)

root.mainloop()

傳回指定的索引項get()

如果get()方法內(nèi)含一個參數(shù),表示傳回這個索引項的元素內(nèi)容。

樣例:建立Listbox后,傳回索引為1的項目。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_12")
root.geometry("300x210")

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=10)
print(lb.get(1))

root.mainloop()

如果在get()方法內(nèi)有兩個參數(shù)時,則表示傳回區(qū)間選項,第一個參數(shù),是區(qū)間的起始
索引項,第二個參數(shù)是區(qū)間的結(jié)束索引項,所傳回的值用元組方式傳回。

from tkinter import *
fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_12")
root.geometry("300x210")

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=10)
print(lb.get(1,3))

root.mainloop()

傳回所選取項目的索引curselection()

這個方法會傳回所選取項目的索引。

樣例:建立列表框,當(dāng)選取項目時,若單擊Print按鈕可以在Python Shell窗口中
打印所選取的內(nèi)容。如果所選取項目超過兩個會用元組傳回。

from tkinter import *
def callback():
    indexs=lb.curselection()
    for index in indexs:
        print(lb.get(index))

fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_14")
root.geometry("300x250")

lb=Listbox(root,selectmode=MULTIPLE)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=5)
btn=Button(root,text="Print",command=callback)
btn.pack(pady=5)
root.mainloop()

檢查指定索引項是否被選取selection_includes()

如果指定索引項被選取會傳回True,否則傳回False。

樣例:檢查索引3的項目是否被選取,如果被選取單擊Check按鈕可以顯示True,
否則顯示False。

from tkinter import *
def callback():
    print(lb.selection_includes(3))

fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_15")
root.geometry("300x250")

lb=Listbox(root,selectmode=MULTIPLE)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(pady=5)
btn=Button(root,text="Check",command=callback)
btn.pack(pady=5)
root.mainloop()

Listbox與事件綁定

虛擬綁定應(yīng)用于單選

當(dāng)Listbox執(zhí)行選取操作時會產(chǎn)生<<ListboxSelect>>虛擬事件,可以由此設(shè)置事件處理程序。

樣例:當(dāng)選擇Listbox中的項目時,可以在上方列出所選的項目。

from tkinter import *
def itemSelected(event):
    obj=event.widget
    index=obj.curselection()
    var.set(obj.get(index))

fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_16")
root.geometry("300x250")

var=StringVar()
lab=Label(root,text="",textvariable=var)
lab.pack(pady=5)

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
lb.bind("<<ListboxSelect>>",itemSelected)
lb.pack(pady=5)

root.mainloop()

當(dāng)單擊Listbox中選項時會產(chǎn)生虛擬的<<ListboxSelect>>事件,此時可以觸發(fā)
itemChanged()方法處理此事件。itemSelected函數(shù)將所選擇的內(nèi)容在上方的標簽中
顯示。event.widget先取得事件對象obj,此例這個對象就是Listbox對象,然后利用
這個obj對象取得所選的項目索引,再由索引取得所選的項目。當(dāng)然也可以省略obj=event.widget
這一行,直接使用原先的Listbox對象lb也可以。

在設(shè)計這類程序時,由于單擊是被tkinter綁定選取Listbox的項目,就用雙擊<Double-Button-1>
方式處理,將所選項目放在標簽上。

lb.binde("<Double-Button-1>",itemSelected)

虛擬綁定應(yīng)用于多選

虛擬綁定的概念也可以應(yīng)用于多選,下面將直接以實例講解。

樣例:當(dāng)選擇多項時,這些被選的項目將被打印出來。這個程序的selectmode使用
EXTENDED。

from tkinter import *
def itemSelected(event):
    obj=event.widget
    indexs=obj.curselection()
    for index in indexs:
        print(obj.get(index))
    print("---------------------")

fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_16")
root.geometry("300x250")

var=StringVar()
lab=Label(root,text="",textvariable=var)
lab.pack(pady=5)

lb=Listbox(root,selectmode=EXTENDED)
for fruit in fruits:
    lb.insert(END,fruit)
lb.bind("<<ListboxSelect>>",itemSelected)
lb.pack(pady=5)

root.mainloop()

活用加入和刪除項目

本節(jié)將以一個比較實用的例子說明加入與刪除Listbox項目的應(yīng)用。

樣例:增加與刪除項目的操作。這個程序有4個Widget控件,Entry是輸入控件,
可以在此輸入項目,輸入完項目后單擊"增加"按鈕,Entry中的項目就會被加入Listbox,
同時Entry將被清空。若是選擇Listbox內(nèi)的項目后再單擊"刪除"按鈕,可以將所選的
項目刪除。

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("ch12_19")

entry=Entry(root)
entry.grid(row=0,column=0,padx=5,pady=5)

btnAdd=Button(root,text="增加",width=10,command=itemAdded)
btnAdd.grid(row=0,column=1,padx=5,pady=5)

lb=Listbox(root)
lb.grid(row=1,column=0,columnspan=2,padx=5,sticky=W)

btnDel=Button(root,text="刪除",width=10,command=itemDeleted)
btnDel.grid(row=2,column=0,padx=5,sticky=W)

root.mainloop()

Listbox項目的排序

在使用Listbox時常需要處理項目排序工作,下面將以實例講解。

樣例:這個程序中單擊"排序"按鈕時默認是從小到大排序,若是勾選復(fù)選框再
單擊"排序"按鈕將從大到小排序。

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("ch12_20")

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
lb.pack(padx=10,pady=5)

btn=Button(root,text="排序",width=10,command=itemsSorted)
btn.pack(side=LEFT,padx=10,pady=5)

var=BooleanVar()
cb=Checkbutton(root,text="從大到小排序",variable=var)
cb.pack(side=LEFT)

root.mainloop()

拖拽Listbox中的項目

在建立Listbox的過程中,另一個很重要的應(yīng)用是可以拖拽選項,下面將以實例講解
這方面的應(yīng)用。

樣例:先建立Listbox,然后可以拖拽所選的項目。

from tkinter import *
def getIndex(event):
    lb.index=lb.nearest(event.y)

def dragJob(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

fruits=["Banana","Watermelon","Pineapple",
        "Orange","Grapes","Mango"]

root=Tk()
root.title("ch12_21")

lb=Listbox(root)
for fruit in fruits:
    lb.insert(END,fruit)
    lb.bind("<Button-1>",getIndex)
    lb.bind("<B1-Motion>",dragJob)

lb.pack(padx=10,pady=10)

root.mainloop()

這個程序中使用了下列方法:
nearest(event.y)

上述代碼可以傳回最接近y坐標在Listbox中的索引。當(dāng)有單擊操作時會觸發(fā)getIndex()方法,
lb.nearest(event.y)可以傳回目前選項的索引。在拖拽過程中會觸發(fā)dragJob()方法,在
newIndex=lb.nearest(event.y)可以傳回新選項的索引,在拖拽過程中這個方法會不斷地
被觸發(fā),至于被觸發(fā)多少次視移動速度而定。

滾動條的設(shè)計

在默認的環(huán)境中Listbox是沒有滾動條的,但是如果選項太多,將造成部分選項無法顯示,此時
可將移動滾動條Scrollbar控件加入Listbox。

注:Scrollbar控件除了可以應(yīng)用在Listbox上,也可以應(yīng)用在Text和Canvas控件上。
它的使用格式如下:
Scrollbar(父對象,options,···)

Scrollbar()方法的第一個參數(shù)是父對象,表示這個滾動條將建立在哪一個窗口內(nèi)。下列是
Scrollbar()方法內(nèi)其他常用的options參數(shù)。
(1)activebackground:當(dāng)光標經(jīng)過滾動條時,滾動條和方向箭頭的顏色。
(2)bg或background:當(dāng)光標沒有經(jīng)過滾動條時,滾動條和方向箭頭的顏色。
(3)borderwidth或bd:邊界寬度,默認是兩個像素。
(4)command:滾動條移動時所觸發(fā)的方法。
(5)cursor:當(dāng)鼠標光標在滾動條上時的光標形狀。
(6)elementborderwidth:滾動條和方向箭頭的外部寬度,默認是1.
(7)highlightborderwidht:當(dāng)滾動條沒有獲得焦點時的顏色。
(8)highlightcorlor:當(dāng)滾動條獲得焦點時的顏色。
(9)highlightthickness:當(dāng)獲得焦點時的厚度,默認是1.
(10)jump:每次短距離地拖拽滾動條時都會觸發(fā)command的方法,默認是0,如果設(shè)為1則
只有放開鼠標按鍵時才會觸發(fā)command的方法。
(11)orient:可設(shè)置HORIZONTAL/VERTICAL分別是水平軸/垂直軸。
(12)repeatdelay:單位是ms,默認是300ms,可以設(shè)置按住滾動條移動的停滯事件。
(13)takefocus:正??梢杂冒碩ab鍵的方式切換滾動條成為焦點,如果設(shè)為0則取消此設(shè)置。
(14)troughcolor:滾動條槽的顏色。
(15)width:滾動條寬,默認是16.

樣例:在Listbox中創(chuàng)建垂直滾動條。

from tkinter import *
root=Tk()
root.title("ch12_21")

scrollbar=Scrollbar(root)
scrollbar.pack(side=RIGHT,fill=Y)

lb=Listbox(root,yscrollcommand=scrollbar.set)
for i in range(50):
    lb.insert(END,"Line "+str(i))
lb.pack(side=LEFT,fill=BOTH,expand=True)
scrollbar.config(command=lb.yview)

root.mainloop()

講解:lb=Listbox(root,yscrollcommand=scrollbar.set)是將Listbox的選項參數(shù)
yscrollcommand設(shè)為scrollbar.set,表示將Listbox與滾動條做連動。

scrollbar.config(command=lb.yview)方法是為scrollbar對象設(shè)置選擇性參數(shù)內(nèi)容,
此例是設(shè)置command參數(shù),也就是當(dāng)移動滾動條時,會去執(zhí)行所指定的方法,此例
是執(zhí)行Listbox對象lb的yview()方法。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容