Monday, 19 July 2021

How do I import user defined variable without creating infinite loop

I keep on getting into a loop when trying to use a user defined variable in another script. But after spending a long time tinkering I can't a way around it and am wondering what I'm doing wrong. My first script (STACK_1) is a GUI in which the user choices options from a checkbox:

import tkinter as tk
from tkinter import font
import os

class MyApp(object):
    
    def __init__(self, parent):
        """Constructor"""
        self.root = parent
        self.root.title("Main frame")
        self.frame = tk.Frame(parent)
        self.frame.pack()

        close_btn = tk.Button(self.frame, text="Close Application", command=self.closeApplication)
        close_btn.pack()

        global lb

        lb = tk.Listbox(self.root, selectmode = "multiple")
        lb.place(relx=0.25, rely=0.5, anchor="center")

        x =["Choice 1", "Choice 2", "Choice 3"]

        for item in range(len(x)):
            lb.insert(tk.END, x[item])
            lb.itemconfig(item, bg="#ffffff")

        tk.Button(self.root, text="Confirm Planets", command=self.confirmSelected).place(relx=0.205, rely=0.62)

        Executefile_btn = tk.Button(self.root, text="Run rando file", command=self.runfile)
        Executefile_btn.place(relx=0.5, rely=0.9)

    def closeApplication(self):
        self.root.destroy()

    def runfile(self):
        os.system('python STACK_3.py')

    def confirmSelected(self):
        planets = []
        cname = lb.curselection()
        for i in cname:
            op = lb.get(i)
            planets.append(op)
            self.planets = planets
        for val in planets:
            print(val)
        if len(planets) < 2:
            print("At least two planets need to be selected")
        return planets

my second script (STACK_2) initialises the other class and forms the GUI itself & saves the list of variables chosen by the user:

import STACK_1
import tkinter as tk

root = tk.Tk()
root.title("N Body Simulation")
root.geometry('400x300')
app = STACK_1.MyApp(root)
root.mainloop()

planets = app.planets

my third script (STACK_3) just prints the list out generated through scripts 1 & 2:

import STACK_1
from STACK_2 import planets

print(planets)

However it keeps looping, as more and more GUI's get produced as script 3 imports script 2 and hence runs it. However I don't see a way of not importing script 2. In addition the print function works only on the subsequent GUI's produced and never the first. I don't understand the latter behaviour nor a way to accomplish this without importing script 2. Any help would be much appreciated.



from How do I import user defined variable without creating infinite loop

No comments:

Post a Comment