浏览文件并使用tkinter显示文件名

时间:2017-06-25 14:10:48

标签: python tkinter

我正在使用此代码浏览视频文件:

def openDirectory(): 
    vidname= tkFileDialog.askopenfile(parent=root, initialdir='/home/', title='Select your video:')
    pathlabel.config(text=os.path.basename(vidname),fg="blue")

但是我收到了这个错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
return self.func(*args)
File "GUI_ubuntu.py", line 15, in openDirectory
pathlabel.config(text=os.path.basename(vidname))
File "/usr/lib/python2.7/posixpath.py", line 114, in basename
i = p.rfind('/') + 1
AttributeError: 'file' object has no attribute 'rfind'

你能帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

tkFileDialog.askopenfile返回以默认读取模式打开的所选文件的文件对象。 所选文件的文件名。

由于您想要询问文件名和路径,因此可以改为使用tkFileDialog.askopenfilename

def openDirectory(): 
    vidname= tkFileDialog.askopenfilename(parent=root, initialdir='/home/', title='Select your video:')
    pathlabel.config(text=os.path.basename(vidname),fg="blue")