Reputation: 3
I have a python tkinter application that is separated in multiple files. Two files hold classes and both get imported to the parent
file where one instance of each is created. However, I need a method of one class to call a method of the other class. How would I do this without creating instances in the child files and importing those? Since each class will be a tkinter Frame and needs a parent I cannot instantiate the child classes inside their respective files.
This is a simple version of what I am trying to do:
parent file: Master.py
import Child1
import Child2
child1 = Child1()
child2 = Child2()
Child 1 file: Child1.py
class Child1():
def __init__(self):
text1 = 'I am Child 1'
def get_called(self):
print(text1)
Child 2 file: Child2.py
class Child2():
def __init__(self):
text2 = 'I am Child 2'
def call_child1(self):
# need to call get_called method of Child1 here
In the final version call_child1
would be called through a tkinter button and run a bunch of other code as well as calling a method of child1.
I am running Python 3.8.1 one windows 10.
Any help is appreciated.
Upvotes: 0
Views: 54
Reputation: 2113
You can pass a child1
instance as argument in your child2
instance :
# parent file: Master.py
import Child1
import Child2
child1 = Child1()
child2 = Child2(child1)
# Child 1 file: Child1.py
class Child1():
def __init__(self):
text1 = 'I am Child 1'
def get_called(self):
print(text1)
# Child 2 file: Child2.py
class Child2():
def __init__(self, ch1):
text2 = 'I am Child 2'
self.child1 = ch1
def call_child1(self):
self.child1.get_called()
# need to call get_called method of Child1 here
Upvotes: 1