tkinter学习笔记之filedialog

本文深入探讨了在GUI编程中如何使用Python的tkinter库进行文件和目录的操作,包括打开文件、保存文件、多文件选择以及目录选择等功能,并提供了替代方案如直接调用Windows的文件对话框。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


https://code.youkuaiyun.com/snippets/1557954



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,但不跨平台



import win32ui

 

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

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

dlg.DoModal()

 

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

print filename


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值