Maddy
Maddy

Reputation: 2060

How to draw grid on window using graphics library in python

I want to draw grid onto the window so that I can easily draw rectangles and know the exact points. I have not been able to figure out a way in python using graphics library. Is there a better method?

I could not find anything online that uses graphics mostly.

This is what I have so far:

from graphics import *

def main():
    win = GraphWin('Floor', 500, 500)
    win.setCoords(0.0, 0.0, 10.0, 10.0)
    win.setBackground("yellow")

    square = Rectangle(Point(5,5), Point(6,6))
    square.draw(win)
    square.setFill("black")

    win.getMouse()
    win.close()

main()

Upvotes: 1

Views: 6599

Answers (1)

adrianus
adrianus

Reputation: 3199

An easy way would be to add a grid just by calculating some pixels yourself:

from graphics import *

def main():
    win = GraphWin('Floor', 500, 500)

    win.setCoords(0.0, 0.0, 10.0, 10.0)
    win.setBackground("yellow")

    # draw grid
    for x in range(10):
        for y in range(10):
            win.plotPixel(x*50, y*50, "blue")

    square = Rectangle(Point(5,5), Point(6,6))
    square.draw(win)
    square.setFill("black")

    win.getMouse()
    win.close()

main()

Which adds a 10x10 pixel grid to your yellow window:

Image with grid

You could do the same by drawing whole lines (as described in the docs) if necessary, at cost of drawing speed (depending on how big your grid size should be).

Upvotes: 2

Related Questions