Reputation: 55
Good people of StackOverflow, I recently started using this package/Python and I encountered a couple of bumps on the way. The logic of my program is to import a CSV file into the user interface then have a run button that will perform a couple of task e.g. like evaluate strings etc. I want to do this in the data_manipulation. I can't seem to be able to get the data frame, to analyse it. Could someone advise what is wrong with the code below? Thank you in advance for any reply. :)
import tkinter as tk
from tkinter.filedialog import askopenfilename
import pandas as pd
import csv
class main:
def __init__(self, csv_file_path, df):
global v
def import_csv_data(self):
self.csv_file_path = askopenfilename()
v.set(self.csv_file_path)
self.df = pd.read_csv(self.csv_file_path)
def data_manipulation(self):
print(self.df)
root = tk.Tk()
tk.Label(root, text="File Path").grid(row=0, column=0)
v = tk.StringVar()
entry = tk.Entry(root, textvariable=v).grid(row=0, column=1)
tk.Button(root, text="Browse Data Set", command=main.import_csv_data).grid(row=1, column=0)
tk.Button(root, text="Close", command=root.destroy).grid(row=1, column=1)
tk.Button(root, text="Run", command=main.data_manipulation).grid(row=1, column=2)
root.mainloop()
Upvotes: 1
Views: 183
Reputation: 168957
The problem is you're trying to use a class as if it was an instance of that class.
While you wouldn't necessarily need a class at all for a program like this, we can still refactor it as one deriving from tk.Tk()
. This also obviates the need for global variables.
import tkinter as tk
from tkinter.filedialog import askopenfilename
import pandas as pd
import csv
class DataAnalysisApp(tk.Tk):
def __init__(self):
super().__init__()
self.csv_file_path = None
self.df = None
self.build_ui()
def import_csv_data(self):
path = askopenfilename()
if not path:
return
self.csv_file_path = path
self.entry_var.set(self.csv_file_path)
self.df = pd.read_csv(self.csv_file_path)
def data_manipulation(self):
print(self.df)
def build_ui(self):
tk.Label(self, text="File Path").grid(row=0, column=0)
self.entry_var = tk.StringVar()
entry = tk.Entry(self, textvariable=self.entry_var).grid(row=0, column=1)
tk.Button(self, text="Browse Data Set", command=self.import_csv_data).grid(row=1, column=0)
tk.Button(self, text="Close", command=self.destroy).grid(row=1, column=1)
tk.Button(self, text="Run", command=self.data_manipulation).grid(row=1, column=2)
app = DataAnalysisApp()
app.mainloop()
Upvotes: 2