Let's say I have two files: code_for_gui.py
and code_for_functions.py
,
in my code_for_gui.py
I have a class:
Class Main_screen_one():
def __init__(self, parent, controller):
Main_screen_one.button_choice = tk.IntVar()
and I have a separate classless function called begin_process()
and begin_process does something very trivial like:
import code_for_gui.py
def begin_process():
print(code_for_gui.Main_screen_one.button_choice.get())
.get() is a tk function to retrieve a value from a user input device (e.g. radio buttons)
When I placed begin_process() in code_for_functions.py
I got an Attribute Error stating that button_choice
is not an attribute of Main_screen_one
, I then tried to change the code to have it as:
def begin_process():
print(code_for_gui.Main_screen_one().button_choice.get())
including the paranthesis in Main_screen_one()
, but then I got another error about not enough parameters being passed as it expected the parent and controller too. So I realize this is wrong, but I'm not entirely sure why?
HOWEVER, when I place begin_process()
into code_for_gui.py
where Class Main_screen_one()
is, I no longer get an error and it works just fine. Can someone please explain why this behavior is happening and where I can potentially read more on this to understand better?
Thank you so much!
CodePudding user response:
The first problem is here (ignoring the obvious syntax error):
Class Main_screen_one():
def __init__(self, parent, controller):
Main_screen_one.button_choice = tk.IntVar()
You're setting button_choice
on the class rather than the instance of the class. It needs to be this:
self.button_choice = tk.IntVar()
The second problem is where you reference it here:
def begin_process():
print(code_for_gui.Main_screen_one.button_choice.get())
You should be accessing the attribute on an instance of a class. That means that somewhere you first need to create an instance, and then use the instance to access the variable:
code_for_gui.ms1 = Main_screen_one(...)
...
print(code_for_gui.ms1.button_choice.get())
CodePudding user response:
Have you initialized the class in the code_for_functions.py
file? That's why you cannot access the variables defined in the __init__()
function. I would have commented but i don't have the rep to do so.