导入模块中的函数无法寻址根模块中的Label



我正在构建一个gui来控制Rasp Pi 4。我有一个主脚本pin_gui1.py。
我的所有控制函数都在pin_control_stub1.py中,我正在导入它。可以在按下按钮时成功运行这些功能。但当函数试图更改根脚本中Label小部件的文本属性时,就会出现错误。

问题:这很好,因为我在主脚本中定义了函数,但如果在导入的脚本中,会得到NameError。您可以看到函数成功运行,我甚至可以从主脚本中传递它们的值,并打印到控制台。但当我尝试更改该标签的文本时,会出现未定义的错误"lbl_command">
要查看此错误,请单击"全部打开"或"全部关闭"按钮。

我的猜测是,导入的scriot中的函数是在导入时编译的,所以主脚本中的其他小部件还没有定义。但我不知道如何拖延(如果这是问题的话(。感谢您的建议。

导入的脚本现在只是一个存根:final将具有全板控制命令,因此所需的结果是能够在名为"lbl_command"的gui底部的标签中显示发送到板的命令。

pin_gui1.py:

#GUI to control Raspberry Pi 4
import tkinter as tk
import pin_control_stub1 as p
# If i define functions here, they can alter text in lbl_command
def randflash():
print("Random Flash 5 sec")
lbl_command["text"] = "Random Flash 5 sec"
m = tk.Tk()
m.title("CONTROL GUI")
m.geometry('500x400')
# This is outside other frames
banner = tk.Label(text="Control Panel for pin_control", fg='cyan', bg='black')
banner.pack()
frame1 = tk.Frame(master=m, width=300, height=200, bg='#888')
frame1.pack(fill='both', expand=True)
btn1 = tk.Button(frame1, width=10, text='Random Flash 5 sec', command=randflash) #command=lambda: p.randflash(5)
btn2 = tk.Button(frame1, width=10,  text='All On', command=p.all_on, fg='green')
btn3 = tk.Button(frame1, width=10,  text='All Off', command=p.all_off, fg='red')
btn1.pack(side='left',padx=5,ipadx=20,ipady=10)
btn2.pack(side='left',padx=5,ipadx=20,ipady=10)
btn3.pack(side='left',padx=5,ipadx=20,ipady=10)
# 2nd frame holds pin/color buttons
frame2 = tk.Frame(master=m, width=300, height=200, relief=tk.SUNKEN, bg='#ccc')
frame2.pack(expand=True, fill="both")
for i in range(len(p.pins)):
txt = 'Pin ' + str(p.pins[i]) + ': ' + p.colors[i]
tk.Button(frame2, width=10,text=txt, command=lambda i=i: p.do_pin(p.pins[i])).grid(pady=2)
frame3 = tk.Frame(master=m, width=300, height=100, bg='#888')
frame3.pack(expand=True, fill='both')
lbl_command = tk.Label(frame3, text=' -- commands --', relief=tk.SUNKEN, bg='#ccc')
lbl_command.pack(ipadx=30)

m.mainloop()

pin_control_stub1.py:

# This stub exists only to test pin_gui1.py on laptop
# The real pin_control.py runs only on Raspberry Pi 4
pins = [12,13,16,21,22,23,24,25]
colors = ['red','green','blue','red','green','blue','yellow','yellow']
# def randflash():
#     print("Random Flash 5 sec")
#     lbl_command["text"] = "Random Flash 5 sec"
def all_on():
print("Turns all on")
lbl_command["text"] = "All ON"
# NOTE: This causes NameError: name 'lbl_command' is not defined.
# Works only if I move this function to pin_gui.py
def all_off():
print("Turns all off")
p.lbl_command["text"] = "All OFF"
# NOTE: This causes NameError: name 'p' is not defined.
# Works only if I move this function to pin_gui.py
def do_pin(x):
print("turns on pin#" + str(x))

对于任何感兴趣的人,以下是我解决这个问题的方法。我终于在这里找到了我需要的提示

在主脚本(pin_gui1.py(中包括这一行,但必须在脚本的末尾

p.addglobals(globals())

然后,在导入的脚本(pin_control_stub1.py(中,包括以下行:

addglobals = lambda x: globals().update(x)

在上面的链接中可以更好地解释这是如何工作的,但它解决了我的问题,并且工作得很完美。

最新更新