获取用Python Zelle图形绘制的图形坐标的颜色

时间:2018-05-13 13:41:16

标签: python zelle-graphics

在python中,如何获得我用Zelle图形模块绘制的任何图形的特定坐标的颜色?

我使用Python和Zelle图形模块来处理我的圈子和线条。我试图在我画的画布上得到一个非特定坐标(或像素?)的颜色。我必须使用什么方法或其他模块来实现这一目标?

我认为getPixel()方法可行,但它不是因为它用于图像处理,而不是用于绘制图片。我目前的代码:

from math import *
from time import *
from graphics import *
def main():
    paper = GraphWin('shjaji20', 300, 300)
    paper.setBackground('white')
    road0 = Circle(Point(150, 150), 100)
    road1 = Line(Point(150, 50), Point(150, 0))
    road2 = Line(Point(50, 150), Point(0, 150))
    road3 = Line(Point(250, 150), Point(300, 150))
    road4 = Line(Point(150, 250), Point(150, 300))


    road0.draw(paper)
    road1.draw(paper)
    road2.draw(paper)
    road3.draw(paper)
    road4.draw(paper)

    car = Circle(Point(0, 150), 5)
    car.setFill('white')
    car.draw(paper)
    for i in range(1000):
        car.move(1, 0)
        time.sleep(.05)
        print car.getPixel(150, 0) ***#I tried many ways but don't work! Here's the problem***

main()

1 个答案:

答案 0 :(得分:1)

这可以通过某种方式完成。 Zelle的graphics.py建立在Python的tkinter库之上,该库既可以标识哪个图形对象位于给定点之上,也可以查询该对象的颜色。关键是要知道GraphWin实例也是继承的tkinter Canvas

from time import sleep
from graphics import *

paper = GraphWin(width=300, height=300)

road = Circle(Point(150, 150), 100)
road.setFill('pink')
road.draw(paper)

Line(Point(150, 50), Point(150, 0)).draw(paper)
Line(Point(50, 150), Point(0, 150)).draw(paper)
Line(Point(250, 150), Point(300, 150)).draw(paper)
Line(Point(150, 250), Point(150, 300)).draw(paper)

car = Circle(Point(0, 150), 5)
car.setFill('white')
car.draw(paper)

for _ in range(300):
    car.move(1, 0)

    center = car.getCenter()
    overlapping = paper.find_overlapping(center.x, center.y, center.x, center.y)
    if overlapping:
        print(paper.itemcget(overlapping[0], "fill"))

    sleep(0.05)

当小圆圈越过线条时,将在控制台上打印“黑色”。当它越过中心圆时,我们将打印“粉红色”。该代码适用于Python3,如果您使用的是Python2,则需要进行调整。