获取tkinter画布上的像素值(为了bloodfill漫水填充而准备的程序)

0 Comments

获取tkinter画布上的像素值(为了bloodfill漫水填充而准备的程序)

from tkinter import *
from PIL import Image
import numpy as np

def get_pixel_color(canvas, x, y):
    """获取tkinter画布上一点的像素值,原理是寻找最上层item,但是如果item表示的是文字
       则返回的并不代表文字区域都是那个fill颜色,因为文字并不是实心的,所以此程序局限性较大,
       也不适合于有图像的.仅做参考,供给有需要的人士阅读"""
    ids = canvas.find_overlapping(x, y, x, y)

    if len(ids) > 0:                 # 说明画布上有item,取最上面的item 
        item = ids[-1]
       
        color = canvas.itemcget(item,"fill") # 获取这个item的fill填充颜色
        color = color.upper()
        if color != '':r,g,b = canvas.winfo_rgb(color)
    else:                            # 否则画布上这个位置没有item,则取背景色     
        r,g,b = canvas.winfo_rgb(canvas.config('bg')[-1])
    r,g,b = r>>8,g>>8,b>>8
    return r,g,b

def get_pixels_of(canvas):
    width = int(canvas["width"])
    height = int(canvas["height"])
    colors = []

    for y in range(height):
        row = []
        for x in range(width):
            row.append(get_pixel_color(canvas, x, y))
        colors.append(row)

    return colors


root  = Tk()
cv = Canvas(width=48,height=36,bg='cyan')
cv.pack()
画布背景色 = cv.winfo_rgb(cv.config('bg')[-1])
r,g,b = 画布背景色
r,g,b = r>>8,g>>8,b>>8
print(r,g,b)

cv.create_text(22,22,text='我',fill='red')

cv.create_oval((5,5,20,16),fill='red',outline='red')
ps = get_pixels_of(cv)

# 把ps中的每个点写入图像
#im = Image.new("RGBA",(480,360))
ps = np.array(ps)
print(ps)

im = Image.fromarray(np.uint8(ps))
im.show()





发表评论