首页 > 解决方案 > 使用 tkinter 接受文件路径时读取 excel 文件时出现断言错误

问题描述

我正在尝试为我的脚本创建一个 GUI,最初我在脚本中硬编码了文件路径,但现在我尝试使用 tkinter 创建一个 GUI,它可以让用户浏览到文件并运行脚本。

这是有效的:

filepath = "E:\\testing in python\\book.xlsx"
df = pd.read_excel(filepath,sheet_name="mysheet")

这就是我正在尝试使用 tkinter 做的事情:

filepath=""
def open_file():
    filepath = filedialog.askopenfilename(initialdir="C:/", title="select file")
    # print(filepath) # it's printing the file path
 
browse_text = tk.StringVar()
browse_btn = tk.Button(root,command=lambda:open_file(),textvariable = browse_text, height=2, width = 10,font = ('Arial',10) )
browse_text.set("Browse")
browse_btn.grid(column = 2, row = 1)
df = pd.read_excel(filepath,sheet_name="mysheet")

我收到此错误:

File "D:\testing in python\script.py", line 64, in <module>
    df = pd.read_excel(filepath,sheet_name= "mysheet")
File "D:\python\lib\site-packages\pandas\util\_decorators.py", line 299, in wrapper
    return func(*args, **kwargs)
  File "D:\python\lib\site-packages\pandas\io\excel\_base.py", line 336, in read_excel
    io = ExcelFile(io, storage_options=storage_options, engine=engine)
  File "D:\python\lib\site-packages\pandas\io\excel\_base.py", line 1071, in __init__
    ext = inspect_excel_format(
  File "D:\python\lib\site-packages\pandas\io\excel\_base.py", line 947, in inspect_excel_format
    assert content_or_path is not None
AssertionError

解决这个问题的最佳方法是什么?

标签: pythonexcelpandastkinter

解决方案


推荐阅读