我对python很新,还在学习。我目前在python中使用import函数时遇到一些困难。 script2.py
包含使我能够使用OLED显示屏的功能。我目前遇到问题,因为调用def primitives
时,我收到一条错误消息,表示尚未定义。
此脚本中的函数(script2.py
)是我要导入script1.py
(原语,main)的内容:
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)
答案 0 :(得分:1)
试试这个: 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)