【问题标题】:Python how to change colour of individual square of grid on mouse clickPython如何在鼠标单击时更改单个网格正方形的颜色
【发布时间】:2018-06-10 04:06:38
【问题描述】:

如何更改网格中单个正方形的颜色。该网格是在图像上绘制的。我计算了网格每个正方形的中心点。当用户单击网格的特定正方形时,我得到该正方形的质心(已经实现)。如何更改网格正方形的颜色。我在变量“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)

我的想法是更改包含在单击的网格正方形中的图像像素的颜色。

我的图书馆是:

import math
from Tkinter import *
from PIL import Image, ImageDraw
import numpy as np

【问题讨论】:

  • 你是如何制作网格的?您使用哪些软件包与图像进行交互?我在代码中看到了 NumPy,但没有提及它或其他库。
  • 我通过输入完整代码更新了问题
  • 我更喜欢快乐的媒介,但我想我会接受的。您使用的是哪个版本的 Python,或者这是一个旨在可在多个版本上运行的库?
  • Python2 版本。
  • 我在 Python2 中设置 Tkinter,然后在 Python3 中进行设置,我转动了我的轮子。应该是一样的,但请告诉我。

标签: python python-2.7 tkinter colors python-imaging-library


【解决方案1】:

你已经完成了艰苦的工作,所以你只需要一个简单的函数,如下所示:

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

您只需在此时调用此函数,而不是打印质心。

John 在他的完整代码中显示(在编辑中删除)画布已经设置为绘制网格。为了设置画布,John 做了:

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 也为:

step_size = int(img.width / step_count)

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

【讨论】:

  • 如何将颜色从红色变为绿色,如果用户想通过鼠标单击相同的矩形来更改颜色,该矩形的颜色通过单击变为红色?
  • 你需要保留一个二维列表,我认为每个单元格被点击了多少次
猜你喜欢
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2015-08-11
  • 2015-12-09
相关资源
最近更新 更多