0

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:

  1. 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?

  2. 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.)

fishbacp
  • 1,123
  • 3
  • 14
  • 29
  • 2
    You would have to `import mymodule`, and use `mymodule.x` to access that variable. (`from mymodule import x` won't work, that just gives you its value at that moment in time.) – jasonharper Jun 26 '21 at 15:26
  • Global is within the module itself, but you need to assign it explicitly if you want to make it visible across other modules. Maybe [this](https://stackoverflow.com/questions/15959534/visibility-of-global-variables-in-imported-modules) can help. – Masoud Rahimi Jun 26 '21 at 15:26
  • Also if your project is big enough that you need multiple files, it's best if you try working with classes. Without classes, big projects are just a pain. – TheLizzard Jun 26 '21 at 15:30
  • @TheLizzard: Thanks. I'm very unaccustomed to using classes. What might my class constructor be for this simple example? Or is the example too simple to illustrate the idea? – fishbacp Jun 26 '21 at 16:41
  • 1
    @fishbacp The code you gave is too short. My recommendation is to look at some Object Oriented Programming tutorials. – TheLizzard Jun 26 '21 at 16:44

0 Answers0