【问题标题】:Get color at point of mouse click in Tkinter在 Tkinter 中单击鼠标点获取颜色
【发布时间】:2021-12-19 12:26:34
【问题描述】:

我正在开发一个程序(在 Linux 中),我需要知道鼠标点击点的颜色。我无法安装外部模块(虽然 PIL 很好)。我确实尝试查看网络中是否发布了解决方案(Return RGB Color of Image Pixel under Mouse Tkinter),但它们似乎都使用了我必须安装的模块。考虑到这些限制,有什么办法可以做到吗?

【问题讨论】:

  • 如果PILPillow模块,那么它有子模块来获取屏幕上像素的颜色。
  • 是的,但如果我没记错的话,您需要为此指定一个图像文件。我想在 Tkinter 窗口上的某个点获取颜色...
  • @RichieHarvy 即使只能使用图像来执行此操作(也许不需要,但是...),PIL 还提供截屏功能,这意味着您可以截屏并获取鼠标指针位置的位置,然后从图像中获取颜色
  • 您可以使用模块io 将PIL 与内存中的图像一起使用,而不是从文件中读取。

标签: python tkinter colors


【解决方案1】:

这是一个简短的脚本,可以在tkinter 中找到并显示颜色。

它使用PIL ImageGrab.grab()pic 抓取整个屏幕,然后您只需按空格键即可找到鼠标指针下的颜色。它使用pic.getpixel(x, y)

import tkinter as tk
from PIL import ImageGrab

master = tk.Tk()
master.columnconfigure(0, weight = 1)
master.title("Colors")

button = tk.Button(master, text = "Press Spacebar")
button.grid(sticky = tk.NSEW)

canvas = tk.Canvas(master, width = 200, height = 200)
canvas.grid(sticky = tk.NSEW)

pic = ImageGrab.grab()

def color():
    x, y = master.winfo_pointerx(), master.winfo_pointery()
    r, g, b = pic.getpixel((x, y))
    hue = f"#{r:02x}{g:02x}{b:02x}"
    button.config( text = f"{x}, {y} =  {hue}")
    canvas["background"] = hue

button["command"] = color
button.focus_force()

master.mainloop()

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 2015-04-09
    • 2015-02-18
    • 2021-08-28
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多