【问题标题】:tkinter - retrieve file name during askopenfiletkinter - 在 askopenfile 期间检索文件名
【发布时间】:2015-09-07 20:13:19
【问题描述】:

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

这是我的“打开文件”方法:

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 返回的任何文件名,但这会返回例如:

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

这当然不是很好。我想要什么 askopenfilename 会返回。但是,如果我调用 askopenfile 和 askopenfilename,用户必须使用两次“打开文件”对话框。

有没有办法在没有第二个对话框的情况下检索文件名?

如果没有,有没有人用正则表达式过滤掉文件名。如果你熟悉 RegEx,最好的文件名当然是 'file.txt' 而不是 '/Users/user/Desktop/file.txt'。不过不管怎样都很好。

【问题讨论】:

    标签: python regex tkinter filenames


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:
      from tkinter import *
      from tkinter import filedialog as fd 
      from PIL import ImageTk, Image
      import os
      
      def openfile():
         filepath= fd.askopenfilename()
         onlyfilename = os.path.basename(filepath)
         mylabel.config(text=onlyfilename)
      
      myscreen=Tk()
      filebutton=Button(text='choose your file',command=openfile)
      filebutton.grid(row=0,column=2)
      mylabel = Label(myscreen, text="You chossen file path will be displayed here")
      mylabel.grid(row=1,column=2)
      myscreen.mainloop()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多