Get color of coordinate of figure drawn with Python Zelle graphics

孤街醉人 提交于 2019-12-11 06:22:20

问题


In python, How can I get the color of a specific coordinate of any figure, that I've drawn with the Zelle graphics module?

I'm using Python with the Zelle graphics module to process with my circles and lines. I'm trying to get a color of aspecific coordinate (or pixel?) on the canvas I'm drawing on. What method or other modules do I have to use in order to achieve this?

I thought the getPixel() method would work, but it does not since it's for image processing, not for drawn pictures. My current code:

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:


This can be done, in a way. Zelle's graphics.py is built atop Python's tkinter library which can both identify which graphic object sits above a given point as well as interrogate that object's color. The key is knowing that a GraphWin instance is also a tkinter Canvas by inheritance:

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)

As the small circle moves across the lines, "black" will be printed to the console. As it moves across the central circle, "pink" we be printed. The code is for Python3, if you're using Python2 you'll need to adjust.



来源:https://stackoverflow.com/questions/50316752/get-color-of-coordinate-of-figure-drawn-with-python-zelle-graphics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!