Horizontal Lines in Tkinter Python
Question: Trying to draw an 8 x 8 grid in Tkinter and I have the vertical lines drawn,
but I can't seem to draw the horizontal lines correctly. Please help!

Here's my code:

    
    
    from tkinter import *
    
    class CanvasGrid:
    def __init__(self):
        self.window = Tk()
        self.window.title("Grid")
        self.canvas = Canvas(self.window, width = 128, height = 128, bg = "white")
        self.canvas.pack()
    
    def displayVertical(self):
        self.canvas.create_line(16, 0, 16, 128, fill = "red",
                                tags = "line")
        self.canvas.create_line(32, 0, 32, 128, fill = "red",
                                tags = "line")
        self.canvas.create_line(48, 0, 48, 128, fill = "red",
                                tags = "line")
        self.canvas.create_line(64, 0, 64, 128, fill = "red",
                                tags = "line")
        self.canvas.create_line(80, 0, 80, 128, fill = "red",
                                tags = "line")
        self.canvas.create_line(96, 0, 96, 128, fill = "red",
                                tags = "line")
        self.canvas.create_line(112, 0, 112, 128, fill = "red",
                                tags = "line")
    
    
    def displayHorizontal(self):
        self.canvas.create_line(50, 50, 50, 50, fill = "blue",
                                tags = "line")
    

Thanks!


Answer: As it is the same code for either direction, you can pass the start values to
a function that creates either/both directions if you want.

    
    
    class CanvasGrid:
        def __init__(self):
            self.window = Tk()
            self.window.title("Grid")
            self.canvas = Canvas(self.window, width=128,
                                height=128, bg = "white")
            self.display_lines(16, 0, 16, 128, "red")
            self.display_lines(0, 16, 128, 16, "blue")
            self.canvas.pack()
    
            self.window.mainloop()
    
        def display_lines(self, x1, y1, x2, y2, color):
            x_plus = x1     ## all lines are evenly spaced
            y_plus = y1
            for ctr in range(7):
                self.canvas.create_line(x1, y1, x2, y2, fill = color)
                x1 += x_plus
                x2 += x_plus
                y1 += y_plus
                y2 += y_plus
    
    CG = CanvasGrid()
    

