小朋友们好,大朋友们好!
我是猫妹,一名爱上Python编程的小学生。
和猫妹学Python,一起趣味学编程。
今日目标
学习下文件对话框,实现打开文件、打开目录、保存文件等功能。
可以通过filedialog模块中的相关函数来实现。
打开文件
打开单个文件
可以通过askopenfilename()函数创建文件对话框,用于打开单个文件,并返回文件的地址。
语法如下:
askopenfilename(filetypes)
filetypes表示打开文件的类型
打开多个文件
可以通过askopenfilenames()函数创建文件对话框,用于打开多个文件,并返回文件的地址所组成的元组。
语法如下:
askopenfilenames()
打开目录
可以通过askdirectory()函数创建文件对话框,用于打开目录,并返回目录的地址。
语法如下:
askdirectory()
保存文件
可以通过asksaveasfilename()函数创建文件对话框,用于保存文件。
语法如下:
askdirectory()
保存文件
可以通过asksaveasfilename(filetypes)函数创建文件对话框,用于保存文件。
语法如下:
asksaveasfilename(filetypes)
filetypes表示保存文件的类型
参考代码
#更多源码->公众号:和猫妹学Python
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.title('文件对话框')
root.geometry('500x400+20+20')
root.resizable(width=False, height=False)
btn_list=['打开单个文件','打开多个文件','打开目录','保存文件']
def opensinglefile():
fileName = tk.filedialog.askopenfilename()
print(fileName)
def openmanyfile():
fileName = tk.filedialog.askopenfilenames()
print(fileName)
def savefile():
fileName = tk.filedialog.asksaveasfilename()
print(fileName)
def opendirectory():
fileName = tk.filedialog.askdirectory()
print(fileName)
tk.Button(root, text=btn_list[0], command=opensinglefile).pack()
tk.Button(root, text=btn_list[1], command=openmanyfile).pack()
tk.Button(root, text=btn_list[2], command=opendirectory).pack()
tk.Button(root, text=btn_list[3], command=savefile).pack()
root.mainloop()
怎么样?
你学会了吗?
好了,我们今天就学到这里吧!
如果遇到什么问题,咱们多多交流,共同解决。
我是猫妹,咱们下次见!