python-filedialog 文件/文件夹 选择器

filedialog提供一系列简易的获取文件路径的方法,它会调用操作系统的文件管理窗口,返回文件路径字符串(字符串列表)、目录字符串或者打开的文件对象(对象列表)。

from tkinter.filedialog import *

def askopenfilename(**options):
    "返回一个文件路径字符串"

    return Open(**options).show()

def asksaveasfilename(**options):
    "返回一个文件路径字符串,文件名是自己输入的"

    return SaveAs(**options).show()

def askopenfilenames(**options):
    "支持多选,返回一个文件路径字符串列表,如果取消的话返回一个空列表"
    
    options["multiple"]=1
    return Open(**options).show()

# FIXME: are the following  perhaps a bit too convenient?

def askopenfile(mode = "r", **options):
    "返回一个只读文件对象"

    filename = Open(**options).show()
    if filename:
        return open(filename, mode)
    return None

def askopenfiles(mode = "r", **options):
    "支持多选,返回一个只读文件对象列表,如果取消的话返回一个空列表"

    files = askopenfilenames(**options)
    if files:
        ofiles=[]
        for filename in files:
            ofiles.append(open(filename, mode))
        files=ofiles
    return files


def asksaveasfile(mode = "w", **options):
    "返回一个可写入的文件对象"

    filename = SaveAs(**options).show()
    if filename:
        return open(filename, mode)
    return None

def askdirectory (**options):
    "返回一个目录路径字符串"
    
    return Directory(**options).show()

实例代码演示

from tkinter import *
import tkinter as tk
import tkinter.filedialog
from PIL import Image,ImageTk
#选择并显示图片
def choosepic():
    path_ = tkinter.filedialog.askopenfilename() #返回一个文件路径的字符串
    path.set(path_)
    #print(path)
    img_open = Image.open(entry.get())
    # img = ImageTk.PhotoImage(img_open.resize((400,400)))
    img = ImageTk.PhotoImage(img_open)
    lableShowImage.config(image=img)
    lableShowImage.image = img

if __name__ == '__main__':
    #生成tk界面 app即主窗口
    app = tk.Tk()
    #修改窗口titile
    app.title("显示图片")
    #设置主窗口的大小和位置
    app.geometry("700x400")
    #Entry widget which allows displaying simple text.
    a=tk.Label(app, text='请选择显示的图片:')
    a.pack()
    path = tk.StringVar()
    entry = tk.Entry(app, state='readonly', text=path, width = 80)
    entry.pack()
    #使用Label显示图片
    lableShowImage = tk.Label(app)
    lableShowImage.pack()
    #选择图片的按钮
    buttonSelImage = tk.Button(app, text='选择图片', command=choosepic)
    buttonSelImage.pack()
    #buttonSelImage.pack(side=tk.BOTTOM)
    #Call the mainloop of Tk.

    app.mainloop()

你可能感兴趣的:(python)