You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 16:45:33