导入函数似乎不起作用

Importing functions does not seem to work

我是 python 的新手,仍在学习中。我目前在 python 中使用导入功能时遇到一些困难。 script2.py 包含使我能够使用 OLED 显示器的功能。我目前遇到问题,因为当调用 def primitives 时,我收到一条错误消息,指出它尚未定义。

此脚本 (script2.py) 中的函数是我要导入到 script1.py 中的函数(原语,主要):

import time
import datetime
from luma.core.render import canvas


def primitives(device, draw):
    # First define some constants to allow easy resizing of shapes.
    padding = 2
    shape_width = 20 
    top = padding
    bottom = device.height - padding - 1
    # Move left to right keeping track of the current x position for drawing shapes.
    x = padding

    # Write two lines of text.
    size = draw.textsize('World!')
    x = device.width - padding - size[0]
    draw.rectangle((x, top + 4, x + size[0], top + size[1]), fill="black")
    draw.rectangle((x, top + 16, x + size[0], top + 16 + size[1]), fill="black")
    draw.text((device.width - padding - size[0], top + 4), 'Hello', fill="cyan") 
    draw.text((device.width - padding - size[0], top + 16), 'World1!', fill="purple") 
    time.sleep(5)


def main():
    from luma.core.interface.serial import spi
    from luma.core.render import canvas
    from luma.oled.device import ssd1351
    serial = spi(device=0, port=0, gpio_DC=20)
    device = ssd1351(serial)
    device.width=128
    device.height=128
    print("Testing basic canvas graphics...")
    for _ in range(2):
        with canvas(device) as draw:
            primitives(device, draw)
            print("Drawing stuff 1")
    time.sleep(3)



    print("Testing clear display...")
    time.sleep(1)
    device.clear()



if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass

正在导入这些函数 (script1.py1) 的脚本是:

import time 
import otherscript


variable_intermediate=1

while True:
    if variable_intermediate==1:
        from script2 import primitives, main #does not seem to work
    main()
    primitives (device, draw) #error printed in terminal, it says draw not defined
    time.sleep(0.01)

试试这个: Script1.py

import time 
import otherscript


variable_intermediate=1

while True:
    if variable_intermediate==1:
        from script2 import primitives, main 
        main() # this is the line you're missing
    time.sleep(0.01)