python Windows tkinter應用開發3 列出目錄的所有檔案
阿新 • • 發佈:2018-12-10
在本章中,我們將編寫程式來執行此操作。
1)選擇資料夾。 2)在UI的標籤部分列印該資料夾中的所有檔名(帶副檔名)。
首先,修改selectFile函式以開啟資料夾。主檔案如下:
from tkinter import * from tkinter import filedialog from Remove import Remove win = Tk() # 1 Create instance win.title("Multitas") # 2 Add a title win.resizable(0, 0) # 3 Disable resizing the GUI win.configure(background='black') # 4 change background color # 5 Create a label aLabel = Label(win, text="Remove duplicate file", anchor="center") aLabel.grid(column=0, row=1) aLabel.configure(foreground="white") aLabel.configure(background="black") # 6 Create a selectFile function to be used by button def selectFile(): #filename = filedialog.askopenfilename(initialdir="/", title="Select file") folder = filedialog.askdirectory() # 7 open a folder then create and start a new thread to print those filenames from the selected folder remove = Remove(folder, aLabel) remove.start() # 8 Adding a Button action = Button(win, text="Open Folder", command=selectFile) action.grid(column=0, row=0) # 9 Position the button action.configure(background='brown') action.configure(foreground='white') win.mainloop() # 10 start GUI
然後在Remove.py中增加使用os.listdir來返回檔案列表:
import threading import os class Remove(threading.Thread): def __init__(self, massage, aLabel): threading.Thread.__init__(self) self.massage = massage self.label = aLabel def run(self): text_filename = '' filepaths = os.listdir(self.massage) for filepath in filepaths: text_filename += filepath + '\n' self.label.config(text=text_filename) return