我怎样才能 - 在我的Python tkinter GUI中 - 允许用户指定我想要存储数据帧的全局变量的名称?

时间:2017-12-27 22:53:39

标签: python tkinter global-variables

在我的tkinter GUI中,用户可以生成一个pandas数据帧(在示例中我采用了固定的数据帧)。 在GUI中,用户可以输入名称并单击“保存”按钮。 我们的想法是将数据帧存储为全局变量,以便在用户离开我的应用程序时可以使用该名称。 我还想跟踪他在组合框中创建的变量。 任何可以帮助我的人都会导致错误消息,例如 全球df          ^ SyntaxError:语法无效

这是我的代码:

#%% 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()

1 个答案:

答案 0 :(得分:2)

Standard way of doing this是将其存储在具有用户所需密钥的字典中,如下所示:

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()

危险且容易出错的方式是使用execeval内置方法,例如here