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

猜你喜欢

转载自my.oschina.net/u/1433482/blog/2986408