In my tkinter GUI the user can generate a pandas dataframe (in the example I take a fixed one). In the GUI the user can enter a name and click the save button. The idea is that the dataframe is than stored as a global variable, so that it is available with that name, when the user leaves my application. I would also like to keep track of the variables he created in a combobox. Anyone who can help me with this results in n error message, such as global df ^ SyntaxError: invalid syntax
Here is my code:
#%% 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()