【发布时间】:2021-08-24 05:53:19
【问题描述】:
我正在尝试使用 tkinter askopenfile() 方法使用“打开”按钮从指定的位置打开文件,如下所示:
def open_file():
file = askopenfile(mode ='r', filetypes =[('text files', '*.txt')])
if file is not None:
content = file.readlines()
btn = Button(root, text ='Open', command = lambda:open_file())
我想在不调用 open_file() 的情况下访问函数外部的“内容”以避免重复打开窗口。我试过这个;
content = None
def open_file():
global content
file = askopenfile(mode ='r', filetypes =[('text files', '*.txt')])
if file is not None:
content = file.readlines()
return content
btn = Button(root, text ='Open', command = lambda:open_file())
print(content)
但我得到的输出为“无”,而不是获取文件内容。这个问题有什么解决办法吗? 提前致谢
【问题讨论】:
-
你的函数中有一个
if file is not None:。如果该语句是False会发生什么,open_file()会返回什么? -
open_file()执行完毕后需要调用print(content),例如另一个按钮触发的函数(当然需要先点击Open按钮),否则会得到@ 987654329@. -
@BrunoLubascher 当文件为无时,它返回空列表和无。虽然,我打开了包含文本的文件,但它返回 None。
-
@acw1668 在代码中,我在 open_file() 执行后调用了 print(content)。但它也没有返回。在执行 mainloop() 函数并且仅关闭 tkinter 窗口之后调用 print 时打印内容。我只想在文件打开后获取主代码中的内容。
-
不,当
print(content)被执行时,你的代码还没有被执行open_file()。你需要研究一下event-driven programming是什么。
标签: python-3.x list function tkinter button