How do I change the color of an individual square of the grid. This grid is drawn over an image. I calculated the center point of each square of the grid. When a user clicks on a specific square of the grid, I get the centroid of that square (already implemented). How can I change the color of the square of the grid. I have centroid of the clicked square in variable "closest_centroid".
# Get closes centroid
def closest_node(node, nodes):
nodes = np.asarray(nodes)
dist = np.sum((nodes - node)**2, axis=1)
return np.argmin(dist)
# print co-ordinate function
def get_coords(event):
mouse_xy = (event.x, event.y)
closest_centroid = centers[closest_node(mouse_xy, centers)]
print(closest_centroid)
My idea is to change the color of pixels of an image contained in the clicked square of the grid.
My libraries are:
import math
from Tkinter import *
from PIL import Image, ImageDraw
import numpy as np
解决方案
You already did the hard work so you just need a simple function like the following:
def change_color(center):
step = step_size/2
center_x, center_y = center
canvas.create_rectangle(
[
center_x - step,
center_y - step,
center_x + step,
center_y + step
],
fill='red'
)
Rather than printing the centroid, you'd just call this function at that point.
John showed in his full code (removed in an edit) that canvas was already setup to draw the grid. To setup canvas John did:
filename = ImageTk.PhotoImage(img)
canvas = tk.Canvas(root,height=img.size[0],width=img.size[0])
canvas.image = filename
canvas.create_image(0,0,anchor='nw',image=filename)
canvas.pack()
Also he has step_size as:
step_size = int(img.width / step_count)
If the image isn't square, you'll need a step_size_x and a step_size_y