tkinter点击浏览按钮选文件后全局变量无法获取文件路径如何解决
问题根因
- 你代码中的
print(filepathforinfo)执行在Information_Window.mainloop()启动之前,这段代码运行时窗口刚完成初始化,你还没有触发按钮点击事件,所以打印的是初始赋值的test。 - 全局变量
filepathforinfo实际上在你点击按钮选择文件后已经被成功修改,只是你没有在修改完成后再读取它的取值。
解决方案
方案1:直接在文件选择完成后执行后续逻辑(更推荐,无需全局变量)
你可以把需要用到文件路径的处理逻辑直接放到get_pdf_file函数里,用户选完文件就直接执行,不需要依赖全局变量传递参数:
import tkinter.filedialog import tkinter as tk def get_pdf_file(): filetypes=[('PDF files', '*.pdf')] filepathforinfo = tk.filedialog.askopenfilename( title='Open a file', initialdir='/', filetypes=filetypes ) # 增加非空判断,避免用户点击取消未选择文件的异常 if not filepathforinfo: return # 选完文件后直接执行后续逻辑 print(filepathforinfo) # get_pdf_info(filepathforinfo) # 窗口初始化逻辑 Information_Window = tk.Tk() Information_Window.title("Information extraction") Information_Window.resizable(True, True) Information_Window['background']='#8c52ff' info_button = tk.Button( Information_Window, text="Give the pdf file to extract information from", activebackground='purple', activeforeground='purple', command=get_pdf_file ) info_button.grid(row=0,column=0) Information_Window.mainloop()
方案2:验证全局变量修改效果
如果你确实需要在其他位置使用这个全局变量,可以增加一个触发逻辑在文件选择完成后读取变量,比如新增一个按钮专门触发打印/处理逻辑:
import tkinter.filedialog import tkinter as tk filepathforinfo='test' def get_pdf_file(): global filepathforinfo filetypes=[('PDF files', '*.pdf')] filepathforinfo = tk.filedialog.askopenfilename( title='Open a file', initialdir='/', filetypes=filetypes ) def process_file(): global filepathforinfo if not filepathforinfo or filepathforinfo == 'test': print("请先选择PDF文件") return print(filepathforinfo) # get_pdf_info(filepathforinfo) # 窗口初始化逻辑 Information_Window = tk.Tk() Information_Window.title("Information extraction") Information_Window.resizable(True, True) Information_Window['background']='#8c52ff' info_button = tk.Button( Information_Window, text="选择PDF文件", activebackground='purple', activeforeground='purple', command=get_pdf_file ) info_button.grid(row=0,column=0) process_button = tk.Button( Information_Window, text="处理选中的文件", activebackground='purple', activeforeground='purple', command=process_file ) process_button.grid(row=0,column=1) Information_Window.mainloop()
内容的提问来源于stack exchange,提问作者Anass
相关产品推荐
相关产品推荐

