python Windows tkinter應用開發3 列出目錄的所有文件

在本章中,我們將編寫程序來執行此操作。

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章