tkinter模块实现文件选择的方法过程是什么
Admin 2022-08-06 群英技术资讯 771 次浏览
学习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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要给大家分享Pytho条件控制语句的内容,主要介绍break、continue和return使用的实例,具有一定的学习价值,感兴趣的朋友可以参考一下,希望大家阅读完这篇文章能有所收获。
结合网上教学内容,指向yield就是迭代器,如果对yield并理解,大家暂且可以把yield理解成“return”,其使用方法与return大致相同,但含义有区别
浏览器到WSGI Server:浏览器发送的请求会先到WSGI Server;environ:WSGI Server会将HTTP请求中的参数等信息封装到environ(一个字典)中。
range函数大多数时常出现在for循环中,在for循环中可做为索引使用,下面这篇文章主要给大家介绍了关于Python中range函数的基本用法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
这篇文章主要为大家介绍了Python 函数的递归,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008