我正在尝试创建一个小的图形用户界面,以转换为XLSX文件。在我的代码中,我目前正在使用tkinter创建一个GUI,然后使用一个函数将其从Parquet转换为XLSX。
然而,当我运行下面的代码时,我仍然得到一个错误,"myfunc()缺少3个必需的位置参数:'txt_file','txt_name‘和'txt_dir'“知道为什么它们没有被赋值吗?
import os
import pandas as pd
from tkinter import *
import pyarrow
import shutil
from pathlib import Path
window = Tk()
window.title("Convertor")
#Sets the size of the window
window.geometry('550x200')
#Adds a header to the window and configures the size
lbl = Label(window, text="Convert Parquet to CSV", font=("Arial Bold", 18))
#Configures where the label message will appear
lbl.grid(column=0, row=0)
#asks for parquet file
lbl2 = Label(window, text="Where is the parquet file currently located?", font=("Arial", 12))
lbl2.grid(column=0, row=1)
#adds a field for an input text message
txt_file = Entry(window,width = 30)
txt_file.grid(column=1, row=1)
#asks for name of xlsx file
lbl3 = Label(window, text="What would you like to call the new xlsx file?", font=("Arial", 12))
lbl3.grid(column=0, row=2)
txt_name = Entry(window,width = 30)
txt_name.grid(column=1, row=2)
#asks where you want to put the new xlsx file
lbl3 = Label(window, text="Where would you like to ouput the xlsx file?", font=("Arial", 12))
lbl3.grid(column=0, row=3)
txt_dir = Entry(window,width = 30)
txt_dir.grid(column=1, row=3)
def myfunc(txt_file, txt_name, txt_dir):
file = txt_file
df1 = pd.read_parquet(file)
df = df1.append(df1, ignore_index=True)
dirout = txt_dir
name = txt_name
cfile = os.path.join(dirout, name + "." + "xlsx")
df.to_excel(cfile)
#Adding a button
btn = Button(window, text="Convert", command=myfunc)
btn.grid(column=1, row = 4)
#The mainloop causes the window to remain open until someone interacts with it
window.mainloop()发布于 2020-01-15 23:05:54
让函数从UI中检索值,而不是将值传递给函数。在本例中,您将小部件保存在全局变量中,这使得这很容易做到。
例如:
def my_func():
file = txt_file.get()
name = txt_name.get()
dir_out = txt_dir.get()
df1 = pd.read_parquet(file)
df = df1.append(df1, ignore_index=True)
cfile = os.path.join(dirout, name + "." + "xlsx")
df.to_excel(cfile)
...
btn = Button(window, text="Convert", command=my_func)如果您希望通过将执行工作的代码放在接受参数的函数中来使代码更易于测试,只需将该代码移动到单独的函数中即可。
def my_func():
file = txt_file.get()
name = txt_name.get()
dir_out = txt_dir.get()
do_conversion(file, name, dir_out)
def do_conversion(file, name, dir_out):
df1 = pd.read_parquet(file)
df = df1.append(df1, ignore_index=True)
cfile = os.path.join(dirout, name + "." + "xlsx")
df.to_excel(cfile)这样,您就可以使用带有或不带有图形用户界面的do_conversion,从而更容易为执行实际转换的代码编写单元测试。
https://stackoverflow.com/questions/59753724
复制相似问题