所以我有两个脚本,一个是主脚本,另一个是次要脚本。主要脚本主要是GUI代码,但我想让其中一个按钮设置一个变量然后调用第二个脚本。然后第二个脚本应该导入变量并继续使用它,但事实并非如此。
我尝试在GUI代码之外预设变量,理论上它应该在按下按钮后改变,但第二个代码只是导入原始变量。
from second import recognition
repeater = True
task = "placeholder"
def resume():
while repeater:
try:
task = "hello"
print(task)
recognition()
def recognition():
import first
task = first.task
print(task)
我认为两个打印功能都会打印“hello”,但是第二个打印功能会打印“占位符”。
编辑:我试过推
global task
下
def resume():
while repeater:
和
try:
但无济于事。
你需要让python知道你要修改全局task
- 否则python将在task
中创建一个名为resume
的新局部变量
在函数内添加global task
声明应该可以完成这项工作
from second import recognition
repeater = True
task = "placeholder"
def resume():
global task
while repeater:
try:
task = "hello"
print(task)
recognition()
你想要的是你的函数中的global
关键字。这导致它使用外部变量。