Skip to content Skip to sidebar Skip to footer

Tkinter - Retrieve File Name During Askopenfile

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 = fi

Solution 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)

Solution 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()

Post a Comment for "Tkinter - Retrieve File Name During Askopenfile"