温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How do I call a file imported through tkinter filedialog?

python - 如何调用通过tkinter filedialog导入的文件?

发布于 2020-03-27 10:38:01

我正在尝试创建一个非常简单的GUI,该GUI将导入文件,通过一些数据格式代码运行它,并将其导出为.xlsx文件。

该文件将是一个excel文件。一个例子是:

col1 
a        
b
c

而我当前的python脚本执行此操作:

df = read_excel('file.xlsx')
mapping = {'a':'apple','b':'banana','c':'carrot'}
df = df.replace({"col1":mapping}, regex=True)

它返回:

col1
apple
banana
carrot

但是现在我正在尝试创建一个将运行它的GUI(:

这是我到目前为止的代码(我收到错误ValueError:DataFrame构造函数未正确调用!):

import tkinter as tk
from tkinter import filedialog
import pandas as pd 
from datetime import datetime, date

def UploadAction(event=None):
    filename = filedialog.askopenfilename()

    print('Selected:', filename)

    df = pd.DataFrame(eval(data=filename))

    mmapping = {'a':'apple','b':'banana','c':'carrot'}

    df = df.replace({"col1":mapping}, regex=True)

    print(df['col1'])

root = tk.Tk()
button = tk.Button(root, text='Open', command=UploadAction)
button.pack()

root.mainloop()

对于excel导出,我知道代码应为:

writer = pd.ExcelWriter("newfile.xlsx",
                        engine='xlsxwriter',
                        datetime_format='yyyymmdd',
                        date_format='yyyymmdd')

df.to_excel(writer, sheet_name = ('Sheet1'))

workbook  = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.set_column('B:C', 20)
writer.save()

但是我不确定如何将其包含在GUI程序中。

那你有什么建议呢?

查看更多

查看更多

提问者
user11642562
被浏览
16
Zaraki Kenpachi 2019-07-03 21:39

你去了:

= ^ .. ^ =

import pandas as pd
import tkinter as tk
from tkinter import filedialog


def open_file():
    # open file
    filename = filedialog.askopenfilename()
    # load data into data frame
    data = pd.read_csv(filename, sep=" ", header=None)

    return data


root = tk.Tk()
button = tk.Button(root, text='Open', command=open_file)
button.pack()

# do something with data
df_data = open_file()
df = df_data.drop(0, axis=1)

# save data to excel
df.to_excel("output.xlsx")

root.mainloop()

发布
问题

分享
好友

手机
浏览

扫码手机浏览