user11794063
user11794063

Reputation:

Import a variable from a class without creating an object of that class

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

Upvotes: 0

Views: 450

Answers (1)

Prune
Prune

Reputation: 77837

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.

Upvotes: 2

Related Questions