如何在函数间传递图片点击的RGB值而不被按钮颜色覆盖?
问题:点击按钮时保存的是按钮颜色而非图片点击的像素颜色
用户需求是:点击图片目标区域获取RGB值,按下按钮保存该值。但当前代码中,点击按钮时保存的是按钮自身的颜色,而非最后一次点击图片的颜色。
问题原因
- 全局绑定左键点击事件:
root.bind('<Button-1>', click)会把所有左键点击(包括点击按钮)都触发click函数,导致点击按钮时会获取按钮的颜色,覆盖之前保存的图片像素颜色。 - 按钮未绑定保存函数:当前代码里的
YellowButton没有关联yellow_calib函数,点击按钮不会执行保存操作。
解决方案
步骤1:仅给图片Label绑定点击事件
将全局窗口的点击绑定改为只给显示图片的Label绑定,这样只有点击图片区域才会触发颜色获取:
# 替换原来的 root.bind('<Button-1>', click) frame.bind('<Button-1>', click)
步骤2:给按钮绑定保存函数
修改按钮的创建代码,添加command参数关联yellow_calib函数:
YellowButton = tk.Button(RightFrame, text="Calib Yellow", command=yellow_calib)
步骤3:初始化selected_color为有效默认值
避免第一次点击按钮时出现空值问题,将selected_color的初始值从空数组改为默认RGB值:
selected_color = [0, 0, 0] # 初始默认颜色,可根据需求调整
修改后的完整代码
import cv2 import numpy as np import tkinter as tk from PIL import Image, ImageTk from ctypes import windll path = "C:/Users/PC/Desktop/M2/venv/paperEval.png" # 读取图片并转换颜色通道 img = cv2.imread(path, cv2.IMREAD_COLOR) b, g, r = cv2.split(img) img = cv2.merge((r, g, b)) root = tk.Tk() im = Image.fromarray(img) imgtk = ImageTk.PhotoImage(image=im) # 初始化选中颜色为默认值 selected_color = [0, 0, 0] def click(event): global selected_color dc = windll.user32.GetDC(0) rgb = windll.gdi32.GetPixel(dc, event.x_root, event.y_root) r = rgb & 0xff g = (rgb >> 8) & 0xff b = (rgb >> 16) & 0xff selected_color = [r, g, b] print("Clicked color : ", selected_color) # 显示图片的Label frame = tk.Label(root, image=imgtk) frame.pack(side=tk.TOP) # 仅给图片Label绑定点击事件 frame.bind('<Button-1>', click) # 颜色设置区域框架 RightFrame = tk.Frame(root) RightFrame.pack(side=tk.BOTTOM) # 存储所有校准颜色的数组 AllColors = np.empty([6, 3], dtype=int) def yellow_calib(): AllColors[0,] = selected_color print("Yellow color : ", AllColors[0,]) # 绑定了保存函数的按钮 YellowButton = tk.Button(RightFrame, text="Calib Yellow", command=yellow_calib) YellowButton.grid(row=0, column=0) root.mainloop()
内容的提问来源于stack exchange,提问作者Hibou
相关产品推荐
相关产品推荐

