简体   繁体   English

在模块之间更改python全局变量

[英]Changing python global variables between modules

I'm trying to carry a change from a global variable over to another module in Python2.7. 我试图将更改从全局变量传递到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: 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. 我希望从RunnerMod.py命名为choice的全局变量继承到该模块。 main_mod: 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. 全局变量选择从0开始,但是我想在RunnerMod.py模块中将其更改为1,并将其反映在main_mod.py模块中。 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. 事实证明,我无法将更改从遍历器的内容传递给RunnerMod.py,因为它是启动程序的模块。 What I had to do was use runnerMod.py to launch the program and then call a function in main_mod.py. 我要做的是使用RunnerMod.py启动程序,然后在main_mod.py中调用一个函数。 This function called BACK to a class in runnerMod.py and loaded up the GUI. 此函数在RunnerMod.py中调用BACK,并加载了GUI。 Only by calling back and THEN modifying the global variable could I pass over the changes. 只有通过回叫并然后修改全局变量,我才能传递所做的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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