简体   繁体   中英

Changing python global variables between modules

I'm trying to carry a change from a global variable over to another module in Python2.7. I've done this in similar situations before but for some reason it won't work in this instance. The first file is the one that runs the program. It sets up a global variable and changes it according to the option selected. I've pasted a bit of the code below. runnerMod:

import Tkinter
from main_mod import*

choice = "0"

def main():
    main_mod=functOne()

class GUI(Tkinter.Tk):
    def __init__(self, parent):
        Tkinter.Tk.__init__(self, parent)
        self.parent = parent
            self.initialize()

    def initialize(self):
        self.grid()
        self.update()
        btnOption1 = Tkinter.Button(self, text=u"Option 1", command=self.onButtonClick)
        btnOption1.grid(column=0, row=1)

    def onButtonClick(self):
        selection = "1"
        self.destroy()
        exec 'choice=%s' %selection in globals()
        main()

class menuSelection:
    def OPTIONCHOSEN(self):
        return choice

if __name == "__main__":
    app = GUI(None)
    app.mainloop

I want the global variable named choice from runnerMod.py to carry over to this module. main_mod:

from runnerMod import menuSelection

def functOne():
    userInput = menuSelection().OPTIONCHOSEN()
    print userInput

The global variable choice starts at 0, but I want to change it to 1 in the runnerMod.py module and have this reflected in the main_mod.py module. Since I'm rewriting an interface to an existing program my options are a little limited in the way its coded. Anyone have any ideas here?

As it turns out, I couldn't pass over changes to a global variable from runnerMod.py because it was the module that launched the program. What I had to do was use runnerMod.py to launch the program and then call a function in main_mod.py. This function called BACK to a class in runnerMod.py and loaded up the GUI. Only by calling back and THEN modifying the global variable could I pass over the changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM