Python 3.9: I believe this is a frequently-asked question, but I can't quite understand how to apply specific suggestions to my small example below.
Suppose I have a function _func()
that is the callback from a button in my main script where the value of a variable x is defined:
def _func():
global x
x=3
Now I have a button whose callback is _func()
:
Mybutton=Button(master=root,text='do it', command=_func)
My understanding is that because x was declared globally, I can now use it at other places in my main script once the button has been pressed.
Two questions:
What if _func is imported from a different module at the start of my main script using
from mymodule import _func as _func
?Now x isn't "remembered" in my main script since it was defined in the loaded module. How do I adjust for this?
My actual script is quite lengthy and I have many imported callback functions. What general suggestions for accomplishing my goal, declaring as few global variables as possible? Would it involve classes and, if so, what would be the particulars? (I'm pretty weak in terms of working with classes.)