Python中p5库运行报错:AttributeError: module '__main__' has no attribute 'preload'
解决p5.py运行时出现的AttributeError: module 'main' has no attribute 'preload'错误
问题重现
运行以下代码时触发错误:
from p5 import setup, draw, size, background, run import numpy as np width = 500 height = 500 def setup(): size(width, height) def draw(): background(51) run()
错误输出:
Traceback (most recent call last): File "c:/Users/Admin/main.py", line 15, in <module> run() File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\p5\sketch\userspace.py", line 160, in run preload_method = __main__.preload AttributeError: module '__main__' has no attribute 'preload'
解决方法
这个错误的核心原因是:p5库的run()函数默认会尝试从主模块中查找preload预加载函数,哪怕你根本不需要用到预加载逻辑。有两种简单的修复方式:
方式1:添加空的preload函数
直接在代码里定义一个空的preload函数,满足库的查找要求即可:
from p5 import setup, draw, size, background, run import numpy as np width = 500 height = 500 def preload(): # 空函数,无需编写任何逻辑 pass def setup(): size(width, height) def draw(): background(51) run()
方式2:修改run()参数,禁用preload检查
调用run()时传入preload=False,明确告诉库不需要加载预加载函数:
from p5 import setup, draw, size, background, run import numpy as np width = 500 height = 500 def setup(): size(width, height) def draw(): background(51) run(preload=False) # 添加该参数跳过preload检查
内容的提问来源于stack exchange,提问作者Mody
相关产品推荐
相关产品推荐

