【问题标题】:global variable not updating (Processing.py)全局变量未更新(Processing.py)
【发布时间】:2020-03-05 16:04:49
【问题描述】:

我正在使用 processing.py 制作一个用于绘制简单线条的应用程序 这是我的代码:

pointsList =[ ]
points = []


def setup():
    global pointsList, points
    size(400,400)
    stroke(255)
    strokeWeight(5)

def draw():
    global pointsList, points
    background(0)
    for points in pointsList:
        draw_points(points)
    draw_points(points)


def keyPressed():
    global pointsList, points
    if key == 'e':
        try:
            pointsList.append(points)
            points = [] #<--- this right here not updating
        except Exception as e:
            print(e)
        print(pointsList)

def mouseClicked():
    global points
    print(points)
    points.append((mouseX,mouseY))


def draw_points(points):
    for i in range(len(points)-1):
        draw_line(points[i],points[i+1])

def draw_line(p1,p2):
    line(p1[0],p1[1],p2[0],p2[1])

在某一时刻我想清除我的“点”数组 但它没有更新

这是什么原因造成的?

【问题讨论】:

  • 你怎么知道它不更新?您是否使用print(points) 来检查它?或者它可能从不运行这部分代码,因此无法更新它。
  • @furas 是的,我检查了打印功能,它在“keyPressed”功能中确实更新,但在“Draw”或“mouseClicked”功能中是一样的
  • 您是否检查过它是否在 if key == 'e': 中运行代码?也许key 不是e 而是E
  • @furas 是的,我做到了,它是“e”
  • 我运行了它,它确实清除了列表,但经过一些更改后它清除了列表,但代码似乎相同。现在我试着找出为什么它现在可以正常工作。

标签: python variables global-variables processing


【解决方案1】:

问题出在不同的地方,因为您在循环for points 中的函数draw() 中使用了相同的名称points,因此它将最后一个元素从pointList 分配给points

您必须在 draw() 中使用不同的名称 - 即。 items

def draw():
    global pointsList, points

    background(0)

    for items in pointsList:  # <-- use `items`
        draw_points(items)    # <-- use `items`

    draw_points(points)

pointsList = []
points = []

def setup():
    global pointsList, points

    size(400,400)
    stroke(255)
    strokeWeight(5)

def draw():
    global pointsList, points

    background(0)

    for items in pointsList:  # <-- use `items`
        draw_points(items)    # <-- use `items`

    draw_points(points)


def keyPressed():
    global pointsList, points

    if key == 'e':
        try:
            pointsList.append(points)
            points = []
        except Exception as e:
            print(e)

        print(pointsList)

def mouseClicked():
    global points

    points.append((mouseX,mouseY))
    print(points)

def draw_points(points):
    for i in range(len(points)-1):
        draw_line(points[i], points[i+1])

def draw_line(p1, p2):
    line(p1[0], p1[1], p2[0], p2[1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多