我如何 - 在我的Python Tkinter GUI中 - 允许用户指定我要存储数据框的全局变量的名称



在我的tkinter gui中,用户可以生成pandas dataframe(在示例中,我采用了固定的一个)。在GUI中,用户可以输入名称,然后单击"保存"按钮。这个想法是,数据帧多于作为全局变量存储,因此当用户离开我的应用程序时,该名称可用。我还想跟踪他在Combobox中创建的变量。任何可以在n错误消息中帮助我的人,例如全球DF ^语法:语法无效

这是我的代码:

#%% Import libraries
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox
import pandas as pd
#%% Main class
class PyDataTest(ttk.Frame):
    def __init__(self, master = None):
        # Construct the Frame object.
        ttk.Frame.__init__(self, master)
        self.grid(sticky=tk.N+tk.S+tk.E+tk.W)
        self.createWidgets()
    def save(self):
        global df 
        df = pd.DataFrame({'AAA' : [1., 2., 3., 4.], 'BBB' : [4., 3., 2., 1.]})
        messagebox.showinfo("Info","pandas dataframe saved as df")
#        eval("global " + self.pythonVar.get())
#        eval(self.pythonVar.get() + " = self.pyTable.data")
#        messagebox.showinfo("Info","pandas dataframe saved as " + self.pythonVar.get())
    #%% Create widgets
    def createWidgets(self):
        # Get top window 
        self.top = self.winfo_toplevel()
        # Make it stretchable         
        self.top.rowconfigure(0, weight=1)
        self.top.columnconfigure(0, weight=1)
        # Allow to enter a name and save the data in the base workspace
        ttk.Label(self, text = "Variable").grid(row = 0, column = 0, sticky = tk.W, padx =5, pady=5)
        self.pythonVar = tk.StringVar()
        self.pythonVar.set('d')
        ttk.Entry(self, textvariable=self.pythonVar).grid(row = 0, column = 1, sticky = tk.W, padx =5, pady=5)
        # Save button
        ttk.Button(self, text = "Save", command=self.save).grid(row = 0, column = 2, sticky = tk.W, padx =5, pady=5)
        # Combobox showing dataframes stored
        ttk.Label(self, text = "Dataframes").grid(row = 1, column = 0, sticky = tk.W, padx =5, pady=5)
        comboboxDataframes = ttk.Combobox(self)
#        variables= [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]
#        comboboxDataframes['values'] = variables
        comboboxDataframes.grid(row = 1, column = 1, sticky = tk.W, padx =5, pady=5)    
#%% Allow the class to run stand-alone.
if __name__ == "__main__":
    PyDataTest().mainloop()

这样做的标准方法是将其存储在具有用户所需键的字典中:

def save(self):
    global df 
    df = pd.DataFrame({'AAA' : [1., 2., 3., 4.], 'BBB' : [4., 3., 2., 1.]})

应该简单地替换为:

def save(self):
    global df
    user_spec = self.pythonVar.get()
    df[user_spec] = pd.DataFrame({'AAA' : [1., 2., 3., 4.], 'BBB' : [4., 3., 2., 1.]})

也将 df宣布为全局范围中的字典,例如在" main"中:

if __name__ == "__main__":
    df = dict()
    PyDataTest().mainloop()

a 危险,易于错误的方法是使用execeval内置方法,例如在此处。

相关内容

  • 没有找到相关文章

最新更新