pandas 在tkinter中有一个全局df

huwehgph  于 2022-11-27  发布在  其他
关注(0)|答案(1)|浏览(136)

你好,我在我的学校的一个项目,我必须编码一个股票经理。

import tkinter as tk
from tkinter import filedialog, messagebox, ttk, simpledialog
from PIL import Image,ImageTk
import pandas as pd

# initalise the tkinter GUI
window = tk.Tk()

window.geometry("1280x720") # set the root dimensions
window.pack_propagate(False) # tells the root to not let the widgets inside it determine its size.
window.resizable(0, 0) # makes the root window fixed in size.
window.title('e-Zone Manager')

bg=tk.PhotoImage(file='image2.png')
canva=tk.Canvas(window)
canva.pack(fill="both",expand=True)
canva.create_image(0,0,image=bg,anchor="nw")

logo=tk.PhotoImage(file="logo.png")
window.iconphoto(False,logo)

# Frame for TreeView
frame = tk.LabelFrame(window,)
frame.place(height=300, width=750, rely=0.2, relx=0.21)

# Frame for open file dialog
data_frame = tk.LabelFrame(window, text="Open File")
data_frame.place(height=100, width=400, rely=0.75, relx=0.05)

#Frame pour les outils
tool_frame=tk.LabelFrame(window)
tool_frame.place(height=100,width=600,rely=0.75,relx=0.45)

# Buttons
button1 = tk.Button(data_frame, text="Browse A File", command=lambda: File_dialog())
button1.place(rely=0.65, relx=0.50)

button2 = tk.Button(data_frame, text="Load File", command=lambda: Load_excel_data())
button2.place(rely=0.65, relx=0.30)

button3 = tk.Button(tool_frame, text="Ajout", command=lambda: ajout())
button3.place(rely=0.65,relx=0.30)

button4=tk.Button(tool_frame,text="Supprimer",command=lambda: supp())
button4.place(rely=0.75,relx=0.40)

# The file/file path text
label_file = ttk.Label(data_frame, text="No File Selected")
label_file.place(rely=0, relx=0)

## Treeview Widget
tv1 = ttk.Treeview(frame)
tv1.place(relheight=1, relwidth=1) # set the height and width of the widget to 100% of its container (frame1).

treescrolly = tk.Scrollbar(frame, orient="vertical", command=tv1.yview) # command means update the yaxis view of the widget
treescrollx = tk.Scrollbar(frame, orient="horizontal", command=tv1.xview) # command means update the xaxis view of the widget
tv1.configure(xscrollcommand=treescrollx.set, yscrollcommand=treescrolly.set) # assign the scrollbars to the Treeview Widget
treescrollx.pack(side="bottom", fill="x") # make the scrollbar fill the x axis of the Treeview widget
treescrolly.pack(side="right", fill="y") # make the scrollbar fill the y axis of the Treeview widget



def File_dialog():
    """This Function will open the file explorer and assign the chosen file path to label_file"""
    filename = filedialog.askopenfilename(initialdir="/",
                                          title="Select A File",
                                          filetype=(("xlsx files", "*.xlsx"),("All Files", "*.*")))
    label_file["text"] = filename
    return None

def refresh_df():
    file_path = label_file["text"]
    excel_filename = r"{}".format(file_path)
    df = pd.read_excel(excel_filename)
    clear_data()
    tv1["column"] = list(df.columns)
    tv1["show"] = "headings"
    for column in tv1["columns"]:
        tv1.heading(column, text=column) # let the column heading = column name
        
    df_rows = df.to_numpy().tolist() # turns the dataframe into a list of lists
    for row in df_rows:
        tv1.insert("", "end", values=row) # inserts each list into the treeview. For parameters see https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview.insert

def Load_excel_data():
    """If the file selected is valid this will load the file into the Treeview"""
    file_path = label_file["text"]
    try:
        excel_filename = r"{}".format(file_path)
        if excel_filename[-4:] == ".csv":
            df = pd.read_csv(excel_filename)
        else:
            df = pd.read_excel(excel_filename)

    except ValueError:
        tk.messagebox.showerror("Information", "The file you have chosen is invalid")
        return None
    except FileNotFoundError:
        tk.messagebox.showerror("Information", f"No such file as {file_path}")
        return None
    clear_data()
    tv1["column"] = list(df.columns)
    tv1["show"] = "headings"
    for column in tv1["columns"]:
        tv1.heading(column, text=column) # let the column heading = column name
        
    df_rows = df.to_numpy().tolist() # turns the dataframe into a list of lists
    for row in df_rows:
        tv1.insert("", "end", values=row)
    return None
    

def clear_data():
    tv1.delete(*tv1.get_children())
    return None

def supp(df):
    ligne_supp=simpledialog.askinteger("Input","Quel ligne voulez vous supprimer ?")
    df=df.drop(ligne_supp)
    #df.reset_index(inplace=True)
    clear_data()
    tv1["column"] = list(df.columns)
    tv1["show"] = "headings"
    for column in tv1["columns"]:
        tv1.heading(column, text=column) # let the column heading = column name
        
    df_rows = df.to_numpy().tolist() # turns the dataframe into a list of lists
    for row in df_rows:
        tv1.insert("", "end", values=row)

window.mainloop()

我的问题是我想有一个全局的数据框架,我可以在我的不同函数中使用,因为现在在每个函数中我写了一个新的df,这不会更新我的GUI中的df。但事实上,我要求我的excel文件的路径,使我不能在我的main()中声明我的df。
如果你有提示或解决方案,我将感激不尽!
我试着在每个函数中上传我的df,但是这写在了我的excel文件中,并创建了一个新的列,所以我不能使用我的函数两次。

qhhrdooz

qhhrdooz1#

全局对象(不推荐)

您需要创建全局对象global variable_name
在每个函数或方法中,需要在函数/方法global variable_name的开头标记要使用该对象

推荐

将df作为函数参数传递,或者创建类并创建内部属性来存储df

相关问题