Python如何在单击鼠标时更改网格的单个正方形的颜色 [英] Python how to change colour of individual square of grid on mouse click

查看:232
本文介绍了Python如何在单击鼠标时更改网格的单个正方形的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改网格的单个正方形的颜色.该网格绘制在图像上.我计算了网格的每个正方形的中心点.当用户单击网格的特定正方形时,我得到了那个正方形的质心(已实现).如何更改网格正方形的颜色.我在变量"closest_centroid"中具有所单击的正方形的质心.

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.

我的图书馆是:

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在他的完整代码(在编辑中删除)中显示,画布已经设置好以绘制网格.要设置John的画布,

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()

他的step_size也为:

Also he has step_size as:

step_size = int(img.width / step_count)

如果图像不是正方形,则需要step_size_xstep_size_y

If the image isn't square, you'll need a step_size_x and a step_size_y

这篇关于Python如何在单击鼠标时更改网格的单个正方形的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆