STOPIMACODER
STOPIMACODER

Reputation: 822

Tkinter how to create a grid?

I currently have a grid using tkinter and wanted to have every individual box to have a onClick function. The one i have just draws the vertical lines and horizontal lines but does not divide it. Should i look at a different approach to build my grid? or is there a way to individually handle every box?

What i'm trying to achieve: on click, the button turns the clicked box to either red, white or green.

Code:

import tkinter as tk

def create_grid(event=None):
    w = c.winfo_width()
    h = c.winfo_height()
    c.delete('grid_line')

    for i in range(0, w, 100):
        c.create_line([(i, 0), (i, h)], tag='grid_line')

    for i in range(0, h, 100):
        c.create_line([(0, i), (w, i)], tag='grid_line')

root = tk.Tk()

c = tk.Canvas(root, height=1000, width=1000, bg='blue')
c.pack(fill=tk.BOTH, expand=True)

c.bind('<Configure>', create_grid)

root.mainloop()

Upvotes: 1

Views: 88

Answers (1)

figbeam
figbeam

Reputation: 7176

Lines do not divide a canvas, you have to place something on the canvas that allows you to set color. In my example I have chosen rectangles.

To hook mouse click you'll have to bind mouse click to the canvas and have a callback function change color of the rectangle under the mouse pointer.

As resizing of the window deletes and creates a new array of rectangles, all color changes will be lost on resize.

import tkinter as tk

def create_grid(event=None):
    c.delete('all')
    w = c.winfo_width()
    h = c.winfo_height()

    # Create rectangles on whole window
    for x in range(0, w, 100):
        for y in range(0, h, 100):
            box = (x, y, x+100, y+100)
            b = c.create_rectangle(box, fill='blue', outline='black')

def click(event):
    # Find the clicked rectangle
    current = event.widget.find_withtag("current")
    rectangle = current[0]

    # Get current fill color of rectangle
    fill = event.widget.itemcget(rectangle, "fill")
    if fill == 'blue': fill = 'red'
    elif fill == 'red': fill = 'white'
    elif fill == 'white': fill = 'green'
    else: fill = 'blue'

    # Set new fill color
    event.widget.itemconfig(rectangle, fill=fill)


root = tk.Tk()

c = tk.Canvas(root, height=300, width=300, highlightthickness=0)
c.pack(fill=tk.BOTH, expand=True)

c.bind('<Configure>', create_grid)
c.bind('<Button-1>', click)     # Bind Left mouse button to function click()

root.mainloop()

Upvotes: 2

Related Questions