展开图形对象列表

时间:2015-09-25 01:17:31

标签: python python-3.x

从以下绘制的图形对象列表中,我被告知undraw所有这些对象,但我不知道如何。

win = GraphWin("plot", 500, 500)          #defines the graphical window to work with
win.setBackground("white")                #white background
win.setCoords(0, -10, 10, 10)             #the specified coordinates are as such
Line(Point(0,0), Point(10,0)).draw(win)   #draws the x-axis for clarity

def plot(fun, color):       #user defines a function (of x) and the colour it appears with

listP = []

for i in range(0,1001):     #I am told to sample points in the interval x(0,10) at the 
                            #specified rate (one thousand times)
    x = i/100                                       
    try:
        y = eval(fun)                                
    except(ZeroDivisionError, ValueError):   #to avoid program crash on division by 0
        pass                                 #or definition errors like log(x) for x=0
    else:
        p = Point(x,y)                       #for every x,y combination, defines a point
        p.draw(win)                          #which is then plotted
        p.setFill(color)                     #and coloured according to specification
        listP.append((x,y))                  #and then added to a list of points

return(listP)                                #in the end I am told to return the list

现在,鉴于此列表,我被告知我应该然后 undraw每一点,但我如何调用现有的点/图形对象?现在尝试为列表p = Point(x,y)中的每一组x,y定义一个点listP,只会创建新点,因此我无法使用p.undraw()

我很想使用“穷人”#34;"简单地在现有的点上绘制一个白色的盒子,但是练习明确地说我应该只是点一点点,它让我绝对难过。

1 个答案:

答案 0 :(得分:0)

我清理了我的代码并使用一些全局定义修复了问题

def plot(window, fun, color):

    global win
    win = GraphWin(window, 500, 500)                        
    win.setBackground("white")
    win.setCoords(0, -10, 10, 10)
    Line(Point(0,0), Point(10,0)).draw(win)

    global listU
    listU = []
    listP = []

    for i in range(0,1001):                             
        x = i/100                                       
        try:
            y = eval(fun)                                
        except(ZeroDivisionError, ValueError):          
            pass
        else:
            p = Point(x,y)                              
            p.draw(win)
            p.setFill(color)
            listP.append((round (x,2),round(y,2)))     
            listU.append(p)                             

    return(listP)

首先,我将win定义移回到plot方法中,但将其设置为全局,因此它可以与其他方法一起使用 - 特别是下面的undraw方法。其次,我添加了一个名为listU的新列表(也称为全局列表),我自己附加点,而不仅仅是它们的坐标(如listP中所示)。

现在,我制作了一个新方法:

def undraw_all():

    for i in listU:
        i.undraw()

现在查看实际点的列表(而不是我最初查看的坐标列表listP),并连续展开每个点。简单干净。