python GUI編程tkinter樣本之分類樹遍曆工具

來源:互聯網
上載者:User

標籤:回調   需要   main   檔案夾   off   err   一個   目錄   img   

摘錄 python核心編程

本節我們將展示一個中級的tkinter應用執行個體,這個應用是一個分類樹遍曆工具:它會從目前的目錄開始,提供一個檔案清單,雙擊列表中任意的其他目錄,就會使得工具切換到新目錄中,用新目錄中的檔案清單代替舊檔案清單。這裡新增了列表框、文字框和捲軸,此外還增加了按一下滑鼠、鍵盤按下、滾動操作等回呼函數。其實,整個應用就是一系列控制項和函數的組合。

 

#python 3.6import osfrom time import sleepfrom tkinter import *#一個產生GUI應用的自訂類class DirList(object):    #建構函式    def __init__(self,initdir=None):        self.top = Tk()#頂層視窗        self.label = Label(self.top,text = ‘尋找檔案工具V1.0‘)#第一個標籤控制項        self.label.pack()        ‘‘‘        StringVar,並不是Python內建的資料類型,而是tkinter模組內的對象。        我們在使用GUI介面編程時,有時候需要跟蹤變數的值的變化,以保證值的變化隨時可以顯示在介面上。而Python無法做到這一點。這裡採用了Tcl工具中對象。        StringVar 、BooleanVar、DoubleVar、IntVar都屬於這類情況        StringVar()儲存了一個string類型變數,預設值是‘‘        get()方法可以得到儲存的值        set()方法設定/更改儲存的值        Variable類,有些控制項如Entry(本例中出現)、Radiobutton,可以通過傳入特定參數直接和一個程式變數綁定,這些參數包括:variable、textvariable、onvalue、offvalue、value        這種綁定是雙向的:如果該變數發生改變,於該變數綁定的控制項也會隨之更新。        ‘‘‘        self.cwd = StringVar(self.top)        #第二個標籤控制項。用於動態展示一些文本資訊        self.dirl = Label(self.top,fg = ‘blue‘,font = (‘Helvetica‘,12,‘bold‘))        self.dirl.pack()                self.dirfm = Frame(self.top)#第一個Frame控制項,一個包含其他控制項的純容器        self.dirsb = Scrollbar(self.dirfm)#主要是提供滾動功能        self.dirsb.pack(side = RIGHT,fill = Y)#捲軸靠右填充整個剩餘空間        ‘‘‘        一個選項列表,指定列表yscrollbar的回呼函數為捲軸的set,同時捲軸的command回調的是列表的yview        可以這麼理解二者的關係:當Listbox改變時(比如使用向上、向下方向鍵改變列表內容時),捲軸調用set方法改變滑塊的位置;        當捲軸的滑塊位置發生變化時,列表將調用yview以展示新的項。        同學們可以將綁定取消,自行觀察現象。        ‘‘‘        self.dirs = Listbox(self.dirfm,height = 15,width = 50,yscrollcommand = self.dirsb.set)        #綁定操作。這意味著將一個回呼函數與按鍵、滑鼠操作或者其他的一些事件串連起來。這裡當雙擊任意條目時,會調用setDirAndGo函數        self.dirs.bind(‘<Double-1>‘,self.setDirAndGo)        self.dirsb.config(command=self.dirs.yview)#這裡同清單控制項的yscrollcommand回調結合起來        self.dirs.pack(side = LEFT,fill = BOTH)        self.dirfm.pack()                self.dirn = Entry(self.top,width = 50,textvariable = self.cwd)#單行文字框。指定了寬度;同時設定了一個可變型別參數textvariable的值        self.dirn.bind(‘<Return>‘,self.doLS)#綁定操作。這裡當敲擊斷行符號鍵時,調用函數doLS        self.dirn.pack()                self.bfm = Frame(self.top)#第二個Frame控制項        #定義了三個按鈕,每個按鈕分別回調不同的函數,並設定了啟用前景色彩、啟用後景色        self.clr = Button(self.bfm,text = ‘清空‘,command = self.clrDir,activeforeground = ‘white‘,activebackground = ‘blue‘)        self.ls = Button(self.bfm,text = ‘搜尋目錄‘,command = self.doLS,activeforeground = ‘white‘,activebackground = ‘green‘)        self.quit = Button(self.bfm,text = ‘退出‘,command = self.top.quit,activeforeground = ‘white‘,activebackground = ‘red‘)                self.clr.pack(side = LEFT)        self.ls.pack(side = LEFT)        self.quit.pack(side = LEFT)        self.bfm.pack()                #建構函式最後一部分,用於初始化GUI程式,以當前工作目錄作為起始點。        if initdir:            self.cwd.set(os.curdir)            self.doLS()    #清空函數,用於清空cwd,包含當前活動目錄           def clrDir(self,ev = None):            self.cwd.set(‘‘)        #設定要遍曆的目錄;最後又調用doLS函數    def setDirAndGo(self,ev = None):        self.last = self.cwd.get()        self.dirs.config(selectbackground = ‘red‘)        check = self.dirs.get(self.dirs.curselection())        if not check:            check = os.curdir        self.cwd.set(check)        self.doLS()        #實現遍曆目錄的功能,這也是整個GUI程式最關鍵的部分。    def doLS(self,ev = None):        error = ‘‘        tdir = self.cwd.get()        #進行一些安全檢查        if not tdir:            tdir = os.curdir        if not os.path.exists(tdir):            error = tdir + ‘: 沒有這個檔案‘        elif not os.path.isdir(tdir):            error = tdir + ‘:不是檔案夾‘        #如果發生錯誤,之前的目錄就會重設為目前的目錄            if error:            self.cwd.set(error)            self.top.update()            sleep(2)            if not (hasattr(self,‘last‘) and self.last):                self.last = os.curdir            self.cwd.set(self.last)            self.dirs.config(selectbackground = ‘LightSkyBlue‘)            self.top.update()            return        #如果一切正常            self.cwd.set(‘正在擷取目標檔案夾內容……‘)        self.top.update()        dirlist = os.listdir(tdir)#擷取實際檔案清單        dirlist.sort()        os.chdir(tdir)                self.dirl.config(text = os.getcwd())        self.dirs.delete(0,END)        self.dirs.insert(END,os.curdir)        self.dirs.insert(END,os.pardir)        for eachFile in dirlist:#替換Listbox中的內容            self.dirs.insert(END,eachFile)        self.cwd.set(os.curdir)        self.dirs.config(selectbackground = ‘LightSkyBlue‘)#主函數,應用程式入口。main函數會建立一個GUI應用,,然後調用mainloop函數來啟動GUI程式def main():    d = DirList(os.curdir)    mainloop()    if __name__ == ‘__main__‘:    main()

運行效果:

 

python GUI編程tkinter樣本之分類樹遍曆工具

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.