【问题标题】:Python - run a Pandas script with a Tkinter GUIPython - 使用 Tkinter GUI 运行 Pandas 脚本
【发布时间】:2020-12-20 15:21:08
【问题描述】:

我正在尝试使用 tkinter 设置 GUI,我使用了这篇文章 - Use Tkinter to Open file, run script and export file 作为 youtube 上的参考和很棒的教程 - https://www.youtube.com/watch?v=D8-snVfekto&t=2374s.

我希望能够浏览文件,执行我拥有的 pandas 脚本(对于这个例子,我只写了一些简单的东西来检查它是否有效)然后保存它。 我遇到了 script_python 函数的一些问题。我得到一个名称“df”未定义错误。 (我之所以称为全局 df,是因为我有一个“在赋值之前引用了局部变量 'df'”错误并且解决了它) 这应该是一个直截了当的解决方案,但不知何故我无法绕过它。 非常感谢!

import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
import pandas as pd




HEIGHT=400 
WIDTH=500


def load():
    name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xslm', '*.xlsx'))])
    if name.endswith('.csv'):
        df = pd.read_csv(name)
    else:
        df = pd.read_excel(name)
    return df


            
def script_python():
    global df
    df = df.drop(columns=['x','y'])
    

def file_save():
    fname = asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),("All files", "*.*")))
    df.to_excel(fname)

root= tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

background_image = tk.PhotoImage(file='pic.png')
background_label =tk.Label(root,image=background_image)
background_label.place(x=0,y=0, relwidth=1,relheight=1)

frame= tk.Frame(root,bg='#80c1ff', bd=5)
frame.place(relx=0.5, rely=0.1,relwidth=0.5,relheight=0.1, anchor= 'n')

button = tk.Button(frame, text= 'Browse file', font=40, command=load) 
button.place(relx=0.5, relwidth=0.5, relheight=1,anchor='n')

lower_frame= tk.Frame(root,bg='#80c1ff',bd=5)
lower_frame.place(relx= 0.5, rely= 0.5, relwidth=0.5, relheight=0.1, anchor='s')

lower_button = tk.Button(lower_frame, text= 'Execute script', font=10,command=script_python) 
lower_button.place(relx=0.5,rely=0.8, relwidth=0.5, relheight=1,anchor='s')

save_button=tk.Button(root, text= 'Save', font=40,command=file_save) 
save_button.pack()



root.mainloop()

【问题讨论】:

    标签: python-3.x pandas tkinter


    【解决方案1】:

    您的file_save() 函数没有将df 声明为global,因此它不“知道”全局df

    【讨论】:

    • 您的 load 返回局部变量 df。我不确定谁使用这个返回值。也许你的意思是这个 df 也是全球性的?
    • 感谢 Lior 的帮助。我希望用load() 加载的df 与script_python() 一起运行...
    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2017-05-25
    相关资源
    最近更新 更多