问题
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()
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 name='/Users/user/Desktop/file.txt' mode='r' encoding='UTF-8'>
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?
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.
回答1:
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)
.
If you want just the base name use os.path.basename:
import os
name = os.path.basename(file.name)
来源:https://stackoverflow.com/questions/32445483/tkinter-retrieve-file-name-during-askopenfile