我尝试在here构建解决方案。我的代码是:
from tkinter import mainloop, Tk, Frame, Button, Label, Canvas, PhotoImage, NW
from tkinter import ttk
from tkinter import filedialog
import tkinter as tk
from PIL import Image, ImageTk
class my_class(tk.Tk):
def __init__(self):
super().__init__()
self.geometry=('1400x1400')
self.filename = ''
my_notebook = ttk.Notebook(self)
my_notebook.pack(pady=5)
self.selections = Frame(my_notebook, width = 1100, height = 700)
self.selections.pack(fill = "both", expand=1)
my_notebook.add(self.selections, text = "Selections")
Button(self.selections, text = "Select an Image", command = self.get_image).place(x=10,y=40)
self.image_frame = Frame(my_notebook, width = 1100, height = 700)
self.image_frame.pack(fill = "both", expand=1)
my_notebook.add(self.image_frame, text = "Image")
self.my_canvas = Canvas(self.image_frame, width=800, height=600, bg="white")
self.my_canvas.pack()
self.rgb_var = tk.StringVar(self.image_frame, '0 0 0')
self.rgb_label = tk.Label(self.image_frame, textvariable = self.rgb_var)
self.rgb_label.pack()
self.image_frame.bind('<Motion>', lambda e: self.get_rgb(e))
def get_image(self):
self.filename = filedialog.askopenfilename(initialdir="D:/Python", title="select a file", filetypes = (("png files","*.png"),("jpg files","*.jpg")))
self.img = Image.open(self.filename)
self.img_rgb = self.img.convert('RGB')
dim_x, dim_y = self.img_rgb.size
self.img_tk = ImageTk.PhotoImage(self.img_rgb.resize((dim_x, dim_y)))
self.my_canvas.create_image(dim_x // 2, dim_y // 2, image = self.img_tk)
def get_rgb(self, event):
x, y = event.x, event.y
try:
rgb = self.img_rgb.getpixel((x, y))
self.rgb_var.set(rgb)
except IndexError:
pass # ignore errors if cursor is outside the image
if __name__ == '__main__':
app = my_class()
app.geometry=('1200x900')
app.mainloop()
我可以使用按钮选择图像。然后我单击(图像)选项卡并在画布上查看所选图像。
我希望当我在图像上移动鼠标指针时,图像下显示的 (rgb_var) 会更新。相反,仅当鼠标指针位于框架内但在画布外时,图像下方的数字才会更新。此外,显示的数字似乎与图像中的像素无关。当鼠标指针位于图像上方时,如何显示(鼠标指针下方)像素的 RGB 值?
要获取图像的 RGB 值,您必须将“运动”事件绑定到画布而不是图像框架,如下所示
self.my_canvas.bind('<Motion>', lambda e: self.get_rgb(e))
当事件绑定到ImageFrame时,坐标从ImageFrame的左上角开始。尽管如此,您还是会得到
的结果 rgb = self.img_rgb.getpixel((x, y))
因为图像在那里,并且 x 和 y 值有效,即使颜色不能精确表示鼠标指针的背景颜色。