python画布按键颜色随机切换,Python如何在单击鼠标时更改网格的单个正方形的颜色...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值