tkinter-在askopenfile期间检索文件名 [英] tkinter - retrieve file name during askopenfile

查看:85
本文介绍了tkinter-在askopenfile期间检索文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Python和tkinter制作的文本编辑器.

I have a text editor made with Python and tkinter.

这是我的打开文件"方法:

This is my 'open file' method:

def onOpen(self):
        file = askopenfile(filetypes=[("Text files", "*.txt")])
        txt = file.read()
        self.text.delete("1.0", END)
        root.title(file)
        self.text.insert(1.0, txt)
        file.close()

我想将窗口标题设置为等于文件名.目前,我正在使用任何askopenfile返回的文件名,但是返回的示例如下:

I would like to set the window title equal to the file name. At the moment I'm using whatever askopenfile return as the file name, but this returns for example:

< _io.TextIOWrapper名称='/Users/user/Desktop/file.txt'mode ='r'encoding ='UTF-8'>

<_io.TextIOWrapper name='/Users/user/Desktop/file.txt' mode='r' encoding='UTF-8'>

这当然不是很好.我想要任何askopenfilename都会返回.但是,如果我调用askopenfile和askopenfilename,则用户必须两次使用打开文件"对话框.

This, of course, isn't very nice. I would like whatever askopenfilename would return. But if I call askopenfile and askopenfilename the user has to use the 'open file' dialog twice.

没有第二个对话框,有没有办法检索文件名?

Is there any way to retrieve the file name without the second dialog?

如果不是,则有人进行RegEx过滤以滤除文件名.如果您对RegEx满意,最好的文件名当然就是'file.txt'而不是'/Users/user/Desktop/file.txt'.无论哪种方式都很好.

If not, does anyone a RegEx to filter out the file name. if you're good with RegEx, the nicest file name would of course be just 'file.txt' not '/Users/user/Desktop/file.txt'. Either way it's fine, though.

推荐答案

您正在传递文件对象,因此您可以看到对文件对象的引用作为标题,您可以使用name = root.title(file.name)从文件对象中获取名称.

You are passing the file object so you see the reference to the file object as the title, you can get the name from the file object with name = root.title(file.name).

如果只想使用基本名称,请使用 os. path.basename :

If you want just the base name use os.path.basename:

import os
name = os.path.basename(file.name)

这篇关于tkinter-在askopenfile期间检索文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆