📜  使用 Tkinter 在Python中的文件资源管理器

📅  最后修改于: 2022-05-13 01:55:26.970000             🧑  作者: Mango

使用 Tkinter 在Python中的文件资源管理器

先决条件: Tkinter 简介

Python提供了各种模块来创建图形程序。其中,Tkinter 提供了创建 GUI 应用程序的最快和最简单的方法。

创建 tkinter 应用程序涉及以下步骤:

  • 导入 Tkinter 模块。
  • 创建主窗口(容器)。
  • 将小部件添加到主窗口
  • 在按钮等小部件上应用事件触发器。

GUI 如下所示:

创建文件资源管理器

为此,我们必须从 Tkinter 导入filedialog模块。文件对话框模块将帮助您打开、保存文件或目录。
为了打开文件资源管理器,我们必须使用方法 askopenfilename()。此函数创建一个文件对话框对象。

下面是实现

Python3
# Python program to create
# a file explorer in Tkinter
  
# import all components
# from the tkinter library
from tkinter import *
  
# import filedialog module
from tkinter import filedialog
  
# Function for opening the
# file explorer window
def browseFiles():
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.txt*"),
                                                       ("all files",
                                                        "*.*")))
      
    # Change label contents
    label_file_explorer.configure(text="File Opened: "+filename)
      
      
                                                                                                  
# Create the root window
window = Tk()
  
# Set window title
window.title('File Explorer')
  
# Set window size
window.geometry("500x500")
  
#Set window background color
window.config(background = "white")
  
# Create a File Explorer label
label_file_explorer = Label(window,
                            text = "File Explorer using Tkinter",
                            width = 100, height = 4,
                            fg = "blue")
  
      
button_explore = Button(window,
                        text = "Browse Files",
                        command = browseFiles)
  
button_exit = Button(window,
                     text = "Exit",
                     command = exit)
  
# Grid method is chosen for placing
# the widgets at respective positions
# in a table like structure by
# specifying rows and columns
label_file_explorer.grid(column = 1, row = 1)
  
button_explore.grid(column = 1, row = 2)
  
button_exit.grid(column = 1,row = 3)
  
# Let the window wait for any events
window.mainloop()


输出:

takinter-filedialog1

takinter-filedialog1

takinter-filedialog1