tkinter模块实现文件选择的方法过程是什么
Admin 2022-08-06 群英技术资讯 1191 次浏览
这篇文章主要介绍“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绘制直方图的具体代码,供大家参考,具体内容如下运行结果如下代码如下from matplotlib import pyplot as pltif __name__ == "__main__": a =
这篇文章主要介绍了在python2中unicode()函数在python3中报错的解决方案,希望给大家做个参考,下次出现这个问题的时候,也知道如何应对
字符串是 Python 中最常用的数据类型。我们一般使用引号来创建字符串。创建字符串很简单,只要为变量分配一个值即可。
这篇文章主要为大家介绍了python组合数据类型,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
Python调用Shell,有两种方法:os.system(cmd)或os.popen(cmd)脚本执行过程中的输出内容,下面这篇文章主要给大家介绍了关于Python面试之os.system()和os.popen()区别的相关资料,需要的朋友可以参考下
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
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