1. 本际云推荐 - 专业推荐VPS、服务器,IDC点评首页
  2. 云主机运维
  3. VPS运维

python使用tkinter模块完成文档挑选作用

使用tkinter模块实现文件选择功能

本篇文章主要介绍了如何使用Python的tkinter模块,实现用户界面中的文档挑选功能,对于需要实现文件选择的程序员具有很强的实用价值。

python使用tkinter模块完成文档挑选作用

训练具体内容

在用户界面中,通过点击图标,弹出窗口选择文件夹或文件。具体实现步骤如下:

代码实现

1.导入库和控制模块

在使用过程中,需要导入tkinter和filedialog模块,示例代码如下:

import tkinter as tk
from tkinter import filedialog

2.编写按钮命令

本程序需要实现单个文件选择、多个文件选择、以及文件夹选择功能。在此,我们分别编写三个按钮命令,示例代码如下:

def select_file():
    #单个文件选择
    selected_file_path=filedialog.askopenfilename()#使用askopenfilename函数选择单个文件
    select_path.set(selected_file_path)
def select_files():
    #多个文件选择
    selected_files_path=filedialog.askopenfilenames()#askopenfilenames函数选择多个文件
    select_path.set('n'.join(selected_files_path))#多个文件的路径用换行符隔开
def select_folder():
    #文件夹选择
    selected_folder=filedialog.askdirectory()#使用askdirectory函数选择文件夹
    select_path.set(selected_folder)

3.窗体初始化及布局

为了能够显示窗口和布局控件,需要使用tk.Tk()方法初始化窗体,并设置标题,同时需要对各控件进行布局,具体示例代码如下:

root=tk.Tk()
root.title("选择文件或文件夹,得到路径")
#初始化Entry控件的textvariable属性值
select_path=tk.StringVar()
#布局控件
tk.Label(root,text="文件路径:").grid(column=0,row=0,rowspan=3)
tk.Entry(root,textvariable=select_path).grid(column=1,row=0,rowspan=3)
tk.Button(root,text="选择单个文件",command=select_file).grid(row=0,column=2)
tk.Button(root,text="选择多个文件",command=select_files).grid(row=1,column=2)
tk.Button(root,text="选择文件夹",command=select_folder).grid(row=2,column=2)
root.mainloop()

4.运行

选择了单个文件的情况

至此,我们就成功地实现了使用Python中的tkinter模块完成文档挑选功能的程序。希望对需要实现类似功能的同学提供了一些帮助。

原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/6802.html