tkinter模块实现文件选择的方法过程是什么
Admin 2022-08-06 群英技术资讯 1366 次浏览
这篇文章主要介绍“tkinter模块实现文件选择的方法过程是什么”的相关知识,下面会通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“tkinter模块实现文件选择的方法过程是什么”文章能帮助大家解决问题。学习Python中,总想做个图形界面,找来找去,找到了tkinter。
练习内容:图形界面中,点击按钮后,利用弹出对话框选择文件(或文件夹)
import tkinter as tk from tkinter import filedialog
此处练习过程中出现的错误:在没有第2个导入语句时,使用 tk.filedialog 后,提示错误,显示
Cannot find reference ‘filedialog’ in 'init.py
我查了“Lib/tkinter/"文件夹,发现里面并没有 tkinter.py,但是有 filedialog.py
我想着:tkinter是库,filedialog是模块吧,
但为啥 tk.filedialog不能用?
反而,在有第2个导入语句时,用 tk.filedialog 和 filedialog 都可以
出错情况 :

正常情况:

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)
注意:三个按钮命令中,变量select_path是主窗体中Entry控件的textvariable属性值,在窗体初始化过程中,需要为其赋值:
select_path = StringVar()
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()

选择了单个文件的情况

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了python udp如何实现同时收发信息,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
在本篇内容中小编给学习python的朋友们整理了关于网络应用开发的相关知识点以及实例内容,需要的朋友们参考下。
python int是什么意思?python中的int()函数用于将一个字符串或数字转换为整型。
这篇文章给大家分享的是有关用python读取mtx文件的内容,其实无论读取mtx文件还是其他格式的文件,都并不困难,接下来一起跟随小编学习一下吧。
这是一个Python脚本,能够批量地将微软Powerpoint文件( ppt或者 pptx)转换为pdf格式。使用说明1、将这个脚本跟PPT文件放置在同一个文件夹
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008