我嘗試使用 askopenfilename 從 Tkinter 獲取 excel 路徑。在獲取路徑之后并閱讀熊貓的excel。發現錯誤
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Pe\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File C:/Users/Pe/AppData/Local/Programs/Python/Python310/Project/GUI.py", line 23, in select_file
read_excelr()
File "C:/Users/Pe/AppData/Local/Programs/Python/Python310/Project/GUI.py", line 26, in read_excelr
df=Pds.read_excel(xlsx) NameError: name 'xlsx' is not defined
你能幫我看一下excel的方法嗎?謝謝
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
import pandas as Pds
##### create the root window
root = tk.Tk()
root.title('Read Excel')
root.resizable(False, False)
root.geometry('750x150')
lbl1 = tk.Label(root, text="Input Excel File")
lbl1.grid(column=0,row=0)
def select_file():
filetypes = (('All files', '*.xlsx'),('text files', '*.txt'))
filename = fd.askopenfilename(title='Open a file',initialdir='/',filetypes=filetypes)
showinfo(title='Selected File',message=filename)
lbl2['text']=(filename)
print(filename)
xlsx = Pds.ExcelFile(filename)
read_excelr()
def read_excelr():
df=Pds.read_excel(xlsx)
print(df)
##### open button
open_button = ttk.Button(root,text='Open a File',command=select_file)
open_button.grid(column=1, row=0)
##### Text edit
lbl2 = tk.Label(root, text='None')
lbl2.grid(column=2,row=0)
##### run the application
root.mainloop()
uj5u.com熱心網友回復:
因為“xlsx”只是一個區域變數,它只在特定的函式中起作用。您可以將 xlsx 傳遞給read_excelr函式。這是修改后的代碼:
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
import pandas as Pds
##### create the root window
root = tk.Tk()
root.title('Read Excel')
root.resizable(False, False)
root.geometry('750x150')
lbl1 = tk.Label(root, text="Input Excel File")
lbl1.grid(column=0,row=0)
def select_file():
filetypes = (('All files', '*.xlsx'),('text files', '*.txt'))
filename = fd.askopenfilename(title='Open a file',initialdir='/',filetypes=filetypes)
showinfo(title='Selected File',message=filename)
lbl2['text']=(filename)
print(filename)
xlsx = Pds.ExcelFile(filename)
read_excelr(xlsx)
def read_excelr(xlsx):
df=Pds.read_excel(xlsx)
print(df)
##### open button
open_button = ttk.Button(root,text='Open a File',command=select_file)
open_button.grid(column=1, row=0)
##### Text edit
lbl2 = tk.Label(root, text='None')
lbl2.grid(column=2,row=0)
##### run the application
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/503713.html
標籤:Python python-3.x 擅长 熊猫 tkinter
上一篇:參考以上個月為名稱的excel檔案以使用VBA將資料粘貼到其中
下一篇:VlookupVBAExcel
