tkinter学习笔记之filedialog

在GUI编程中,打开文件、目录等是常见操作


https://code.csdn.net/snippets/1557954


tkinter学习笔记之filedialog_第1张图片

from tkinter.filedialog import *
from tkinter import *

filename = askopenfilename(initialdir ='E:/Python')

print filename


除了askopenfilename外,还有函数
保存文件
def asksaveasfilename(**options):
    "Ask for a filename to save as"

打开多个文件
def askopenfilenames(**options):
    """Ask for multiple filenames to open

    Returns a list of filenames or empty list if
    cancel button selected
    """
   
下面的可能更简单些

def askopenfile(mode = "r", **options):
    "Ask for a filename to open, and returned the opened file"

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

def askopenfiles(mode = "r", **options):
    """Ask for multiple filenames and return the open file
    objects

    returns a list of open file objects or an empty list if
    cancel selected
    """

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


def asksaveasfile(mode = "w", **options):
    "Ask for a filename to save as, and returned the opened file"

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


目录选择
def askdirectory (**options):
    "Ask for a directory, and return the file name"
    return Directory(**options).show()





除此之外还有直接调用windows,但不跨平台

tkinter学习笔记之filedialog_第2张图片

import win32ui

 

dlg = win32ui.CreateFileDialog(1) # 1表示打开文件对话框

dlg.SetOFNInitialDir('E:/Python') # 设置打开文件对话框中的初始显示目录

dlg.DoModal()

 

filename = dlg.GetPathName() # 获取选择的文件名称

print filename


这个打开文件对话框的界面比较友好,是Windows本地风格的,中文显示也正常,但缺点是只能在Windows上有效:

你可能感兴趣的:(笔记,tkinter)