在 'A' python 脚本中设置字符串 'B' python 脚本

Set string in 'A' python script from 'B' python script

我有两个脚本:

A.py(是TKwindow)

def function():
    string = StringVar()
    string.set("Hello I'm A.py")

来自 B.py 我希望更改出现在 Tk window 中的字符串。

def changestring():
    string.set("Hello I'm B.py")

显然不行!如何从另一个 python 脚本更改字符串?

变量有作用域。您不能从另一个函数访问一个函数范围内的变量。

关于 A 和 B 的代码 "knows" 必须有一些共同点。该代码应该将变量从一个传递到另一个。

基于此评论:

A.py is the graphic and B is the core with a infinite loop that listen the USB interrupt

我会说您需要两个对象来实现这两个功能,我们称它们为 "graphic" 和 "usb"。其中一个必须 "know" 关于另一个。 "graphic" 应该观察 "usb",或者 "usb" 应该更新 "graphic"。

例如:

# possibly in A.py:

class Graphic(object):
    def __init__(self):
        self.string = StringVar()

    def function(self):
        self.string.set("Hello I'm A.py")


# possibly in B.py:

class USB(object):
    def __init__(self, graphic):
        self.graphic = graphic

    def changestring(self):
        self.graphic.string.set("Hello I'm B.py")


# somewhere:

from A import Graphic
from B import USB

def main():
    graphic = Graphic()
    usb = USB(graphic)
    #...
    usb.changestring()