如何解决使用tkinter返回文件路径
我有一个文件对话框,用于在tkinter
中打开文件。我正在使用tkinter
和askopenfile()
来获取文件名,如下所示。现在,我希望能够访问file_opener()
函数外部的文件路径。
from tkinter import *
from tkinter import filedialog as fd
base = Tk()
base.geometry('150x150')
def file_opener():
file = fd.askopenfile()
if file:
y = file.name
def file():
f = open(y,'r') #Here i want to use value of y from above function
x = Button(base,text='Select a .txt/.csv file',command=lambda: file_opener())
x.pack()
mainloop()
解决方法
您需要使用return
返回值。修改后的代码:
from tkinter import *
from tkinter import filedialog as fd
base = Tk()
base.geometry('150x150')
def file_opener():
file = fd.askopenfile()
if file:
return file.name
def file():
f=open(file_opener(),'r') #Here i want to use value of y from above function
print(f.read())
x = Button(base,text ='Select a .txt/.csv file',command = lambda:file())
x.pack()
mainloop()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。