I have two tkinter class1.py and class2.py . I face the problem that when i import the class2.py in class1.py it executes the class2.py first then only execute class1.py .
###class 1.py
import tkinter as tk
import class2
from class2 import root2
class MyApp1(object):
def __init__(self, parent):
self.root1 = parent
self.root1.title("Main frame")
self.frame = tk.Frame(parent)
self.frame.pack()
btn = tk.Button(self.frame, text="Open Frame", command=)
btn.pack()
def call(self):
self.root1.withdraw()
x = class2.MyApp2(root2)
root1 = tk.Tk()
root1.geometry("800x600")
app = MyApp1(root1)
root1.mainloop()
###class2.py
import tkinter as tk
class MyApp2(object):
def __init__(self, parent):
self.root2 = parent
self.root2.title("Main frame")
self.frame = tk.Frame(parent)
self.frame.pack()
btn = tk.Button(self.frame, text="Open Frame", command=self.openFrame)
btn.pack()
def openFrame(self):
pass
root2 = tk.Tk()
root2.geometry("800x600")
#app = MyApp2(root2)
root2.mainloop()
Now How can I import the class2.py from the class1.py and outcome becomes class1 tkinter window then only class2 tkinter window?
You should not be importing code like this. The proper way to make your code importable is to make sure it only has functions and class definitions. Then, the code that does the importing is responsible for calling the functions and instantiating the classes.
class2.py should look something like this:
import tkinter as tk
class MyApp2(object):
def __init__(self, parent):
self.root2 = parent
self.root2.title("Main frame")
self.frame = tk.Frame(parent)
self.frame.pack()
btn = tk.Button(self.frame, text="Open Frame", command=self.openFrame)
btn.pack()
def openFrame(self):
pass
class1.py can now safely import this file. It can then create the instance of MyApp2
like this:
def call(self):
self.root1.withdraw()
new_window = tk.Toplevel()
class2.MyApp2(new_window)
Or, if you no longer need the main window, you can destroy everything inside the main window and then reuse it for the new class:
def call(self):
for child in self.root1.winfo_children():
child.destroy()
class2.MyApp2(self.root1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.