在graphics.py窗口中通过鼠标单击创建绘制点列表

时间:2016-05-16 15:31:06

标签: loops plot window points zelle-graphics

我正在尝试创建一个用户在窗口中单击的程序,这将创建一个也在窗口中绘制的存储点列表。用户可以根据需要单击多次,但是一旦他们在显示"完成"的矩形内单击。在左下方,列表已完成。

我一直坚持创建循环,允许用户绘制点,直到他们点击"完成"。

这是我到目前为止(我知道我失踪了很多):

from graphics import *
def main():
    plot=GraphWin("Plot Me!",400,400)
    plot.setCoords(0,0,4,4)


    button=Text(Point(.3,.2),"Done")
    button.draw(plot)
    Rectangle(Point(0,0),Point(.6,.4)).draw(plot)

    #Create as many points as the user wants and store in a list
    count=0  #This will keep track of the number of points.
    xstr=plot.getMouse()
    x=xstr.getX()
    y=xstr.getY()
    if (x>.6) and (y>.4):
        count=count+1
        xstr.draw(plot)
    else: #if they click within the "Done" rectangle, the list is complete.
        button.setText("Thank you!")


main()

从用户点击图形窗口中创建存储点列表的最佳方法是什么?我打算稍后使用这些点,但我只是想先存储点。

1 个答案:

答案 0 :(得分:0)

您的代码的主要问题是:您错过了收集和测试点的循环;您的and测试,看看用户点击框中的用户是否应该是or测试;没有足够的时间让用户看到"谢谢!"窗口关闭前的消息。

要收集您的积分,您可以使用数组而不是count变量,只需让数组的长度代表计数。下面是代码的返工,解决了上述问题:

import time
from graphics import *

box_limit = Point(0.8, 0.4)

def main():
    plot = GraphWin("Plot Me!", 400, 400)
    plot.setCoords(0, 0, 4, 4)


    button = Text(Point(box_limit.getX() / 2, box_limit.getY() / 2), "Done")
    button.draw(plot)
    Rectangle(Point(0.05, 0), box_limit).draw(plot)

    # Create as many points as the user wants and store in a list
    point = plot.getMouse()
    x, y = point.getX(), point.getY()

    points = [point]  # This will keep track of the points.

    while x > box_limit.getX() or y > box_limit.getY():
        point.draw(plot)
        point = plot.getMouse()
        x, y = point.getX(), point.getY()
        points.append(point)

    # if they click within the "Done" rectangle, the list is complete.
    button.setText("Thank you!")

    time.sleep(2)  # Give user time to read "Thank you!"
    plot.close()

    # ignore last point as it was used to exit
    print([(point.getX(), point.getY()) for point in points[:-1]])

main()