在 Python 模式下使用 Processing PGraphics? [英] Using Processing PGraphics in Python Mode?

查看:52
本文介绍了在 Python 模式下使用 Processing PGraphics?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Processing 的 Java 模式中,您可以通过全局声明 PGraphics 对象,在 setup() 中使用 createGraphics() 设置它们,然后在 draw() 中引用它们来使用它们.

In Processing's Java Mode, you use PGraphics objects by declaring them globally, setting them up with createGraphics() in setup() and then referring to them in draw().

在Python模式下,做什么不是那么清楚,似乎没有文档解释.你不能在 Python 中声明变量,变量不是自动全局的,也就是说,如果我只是在 setup() c = createGraphics(400,400) 中说,然后在 draw() 中说 c.beginDraw() 我得到一个 NameError: global name 'c' is not defined 这不能简单地通过在上面的行中说 global c 来解决.

In the Python mode, what to do is not so clear and doesn't seem to be explained by the documentation. You can't declare variables in Python and variables are not automatically global, i.e. if I just say in setup() c = createGraphics(400,400) and then in draw() say c.beginDraw() I get a NameError: global name 'c' is not defined and this can't simply be fixed by saying global c in the line above.

那它是怎么做的?

推荐答案

可以使用 global 修复.一定要在你初始化画布的地方使用 global,否则它是一个局部变量,你的全局画布引用可能仍然是 None

It can be fixed using global. Be sure to use global where you initialise the canvas too, otherwise it's a local variable and your global canvas reference may still be None

这是一个基本示例:

# global reference
canvas = None

def setup():
    size(300, 300)
    # setup global canvas
    global canvas
    canvas = createGraphics(300, 300)

    canvas.beginDraw()
    canvas.background(0);
    canvas.noStroke()
    canvas.blendMode(DIFFERENCE)
    canvas.ellipse(150,150,150,150)
    canvas.endDraw()

def draw():
    # reference global canvas to draw
    global canvas
    image(canvas,0,0)

def mouseDragged():
    diameter = dist(mouseX,mouseY,pmouseX,pmouseY)
    # reference global canvas to update graphics
    global canvas
    canvas.beginDraw()
    canvas.ellipse(mouseX,mouseY,diameter,diameter)
    canvas.endDraw()

这篇关于在 Python 模式下使用 Processing PGraphics?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆