天天看点

python gui选择文件_GUI中选择文件

askopenfilename(**options) 返回打开的文件名

askopenfilenames(**options) 返回打开的多个文件名列表

askopenfile(**options) 返回打开文件对象

askopenfiles(**options) 返回打开的文件对象的列表

askdirectory(**options) 返回目录名

asksaveasfile(**options) 返回保存的文件对象

asksaveasfilename(**options) 返回保存的文件名

参数options的常见值如下:

defaultextension 默认后缀:.xxx 用户没有输入则自动添加

filetypes=[(label1,pattern1),(labe2,patt ern2)] 文件显示过滤器

initialdir 初始目录

initialfile 初始文件

parent 父窗口,默认根窗口

title 窗口标题

#coding=utf-8

from tkinter import *

from tkinter.filedialog import *

class Application(Frame):

def __init__(self,master):

super().__init__(master)

self.master=master

self.pack()

self.createWidget()

def createWidget(self):

self.btn=Button(self,text="选择文件",command=self.test1)

self.btn.pack()

self.label=Label(self,bg='green',width=200,height=2)

self.label.pack()

def test1(self):

#选择文件后返回文件名称-字符串

'''

initialdir='f:\\电影1' 表示默认打开F盘里的'电影1'目录

filetypes=[("视频文件","mp4")] 表示只过滤出MP4的视频文件

'''

#askopenfilename()不是一个组件,所以不能传递当前对象self

self.af=askopenfilename(title="上传文件",initialdir='f:\\电影1',filetypes=[("视频文件","mp4")])

#将选择的文件获取的文件名称赋值给标签组件的text属性,用于回显出来

self.label["text"]=self.af

if __name__=="__main__":

root=Tk()

root.title("选择文件")

root.geometry("350x300")

app=Application(root)

root.mainloop()

python gui选择文件_GUI中选择文件

选择文件1.png

python gui选择文件_GUI中选择文件

选择文件2.png

#coding=utf-8

from tkinter import *

from tkinter.filedialog import *

class Application(Frame):

def __init__(self,master):

super().__init__(master)

self.master=master

self.pack()

self.createWidget()

def createWidget(self):

self.btn=Button(self,text="选择文件",command=self.test1)

self.btn.pack()

self.label=Label(self,bg='green',width=200,height=10)

self.label.pack()

def test1(self):

#选打开文件后返回文件对象

'''

initialdir='E:\\HDCZU_Test\\Test' 表示默认打开E盘里的'HDCZU_Test\Test'目录

filetypes=[("文本文件","txt")] 表示只过滤出txt的文本文件

'''

#askopenfile()不是一个组件,所以不能传递当前对象self

with askopenfile(title="读取文件",initialdir='E:\\HDCZU_Test\\Test',filetypes=[("文本文件","txt")]) as f:

self.label["text"] = f.read() #将选择打开的文件获取的文件对象读取出来赋值给Label标签的text属性,用于回显出来

if __name__=="__main__":

root=Tk()

root.title("选择文件")

root.geometry("350x300")

app=Application(root)

root.mainloop()

python gui选择文件_GUI中选择文件

选择文件3.png

python gui选择文件_GUI中选择文件

选择文件4.png