Reputation: 41
Checked:
Tkinter - How to pass instance variable to another class?
and other web resources but didn't find a solution.
I have a Tkinter button to open file:
import tkinter as tk
from tkinter import filedialog as fd
from myClass import my_function
class select_file:
def __init__(self):
self.root = tk.Tk()
self.filename = ""
tk.Button(self.root, text="Browse", command=self.open).pack()
self.root.mainloop()
def open(self):
filetypes = (('LOG files', '*.LOG'), ('All files', '*.*'))
self.filename = fd.askopenfilename(title='open LOG file', filetypes=filetypes)
self.root.destroy()
print(self.filename)
return self.filename
and that's work fine since I can get the file path in right way.
Output:
C:/Users/xxxx/xxxxx/Dataset/SC180918.LOG
My question is how I can pass the selected filename as instance variable to other function within same project but in another file (myClass.py):
class my_function:
log_frame = pd.DataFrame()
def __init__(self, file):
self.file = file
def create_df(self):
myClass.log_frame = pd.read_table(self.file, sep=';', index_col='TimeStamp', parse_dates=True)
return myClass.log_frame
My task is to pass the file to create_df. I tried several code I will not post to avoid confusion and not working code.
Upvotes: 1
Views: 176
Reputation: 730
As the file is important, I generated two python files as below:
myClass.py:
class my_function:
def __init__(self, file):
self.file = file
def create_df(self):
print("filename in my_function is ",self.file)
testMe.py:
import tkinter as tk
from tkinter import filedialog as fd
from myClass import my_function
class select_file:
def __init__(self):
self.root = tk.Tk()
self.filename = ""
tk.Button(self.root, text="Browse", command=self.open).pack()
self.root.mainloop()
def open(self):
filetypes = (('LOG files', '*.LOG'), ('All files', '*.*'))
self.filename = fd.askopenfilename(title='open LOG file', filetypes=filetypes)
self.root.destroy()
print("filename in select_file is ",self.filename)
return self.filename
sfClass = select_file() # select filename by Browse
filename = sfClass.filename # get filename from the class
mfClass = my_function(filename) # pass it to the class
mfClass.create_df()
here is the output if I select testMe.py file:
filename in select_file is C:/Users/XXX/XXX/SOquestions/testMe.py
filename in my_function is C:/Users/XXX/XXX/SOquestions/testMe.py
as a result, filename has been successfully passed to the my_function
.
I tested as below as well:
print(mfClass.file)
it prints: C:/Users/XXX/XXX/SOquestions/testMe.py
Upvotes: 1
Reputation: 730
I would do as following;
sfClass = select_file() # select filename by Browse
filename = sfClass.filename # get filename from the class
mfClass = my_function(filename) # pass it to the class
Upvotes: 1