0

I have 2 files, one.py and two.py, one.py is my main file which i want to run to start my program, I want to access a variable from the GUI class from one.py into another file, without creating an object of that class, as that would create another window

Is this possible?

If so, can i modify the variable and then send it back to one.py

File one.py:

import tkinter

class GUI(tkinter.Tk):
    def __init__(self):
        super().__init__()

        self.var = 'value'

        self.mainloop()


if __name__ == '__main__':
    app = GUI()

File two.py:

from one import GUI

print(GUI().var)    #this creates another window, i dont want that
2
  • if you don't want to create window from first file then don't keep var inside class. OR keep it as class variable, not instance variable. Commented Aug 14, 2020 at 23:06
  • 1
    I don't know how you run second file but if you first start window from first file and later somehow run second file then maybe you should send this value as argument to second file - ie. os.system(f"python two.py {app.var}") and in second file use sys.argv to get it. OR if you import two in first file then you should run two.somefunction(app.var) without importing one in second file` Commented Aug 14, 2020 at 23:11

1 Answer 1

2

Your problem is that you created an instance attribute, not a class attribute. var is created individually for each instance you make. Therefore, you cannot access it independently: until you instantiate a GUI, that variable does not exist.

What you want is a class attribute. You create it at the class level:

class GUI(tkinter.Tk):

    GUI_var = 'value'

    def __init__(self):
        super().__init__()

        self.mainloop()

print (GUI.GUI_var)

This creates one instance of GUI_var, initialized when you define the class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.