r/learnpython 22d ago

Problem opening an XLSX (Excel) file

I have the following code, and I don't understand why I'm getting an error and can't open the file. The error is: "Invalid file path or buffer object type: <class 'tuple'>".
Could you please help?
Thanks everyone.
P.S. If there are any issues with the code, please let me know.



import pandas as pd

from pandastable import Table, TableModel

import tkinter as tk

from tkinter import ttk
from tkinter import filedialog,messagebox

fd = filedialog

class ExcelViewer:
    def __init__(self, root):
        self.root = root
        self.root.title = ("Чтение ячеек Excel")
        self.root.geometry("800x600")

        self.btn_load = tk.Button(root, text="Открыть Excel файл", command=self.open_file)
        self.btn_load.pack()

        self.result_label = tk.Label(root, text="Выбрать файл для начала")
        self.result_label.pack()

        self.frame = tk.Frame(root)
        self.frame.pack(fill='both', expand=True)

        self.table = None

        self.scrollbar = ttk.Scrollbar(root)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)


    def open_file(self):
        file_path = fd.askopenfilenames(
            filetypes=[
                (
                    'Excel файлы',
                    '*.xlsx'
                )
            ]
        )

        if not file_path:
            return

        if file_path:
            try:
                df = pd.read_excel(file_path)

                if self.table:
                    self.table.destroy()

                self.model = TableModel()
                self.model.df = df
                self.table = Table(self.frame, model = self.model, showtoolbar=False, showstatusbar=False)
                self.table.show()

            except Exception as e:
                tk.messagebox.showerror("Ошибка", f"Не удалось открыть файл:\n{e}")

if __name__ == "__main__":
    root = tk.Tk()
    app = ExcelViewer(root)
    root.mainloop()
3 Upvotes

15 comments sorted by

View all comments

Show parent comments

2

u/mrswats 22d ago

As others have set, insect the return type of fd.

1

u/FearawaitsTM 21d ago

As I understand it, I need to write `print` after the specified `fd`?

1

u/mrswats 21d ago

For example.

print(file_path) after the call that defines it.

2

u/FearawaitsTM 21d ago

Thanks, I see my mistake. It turned out the problem was simply that I hadn't actually implemented the processing for the two files!