有没有一种方法可以将tkinter的“绘图”转换为字节数组?

时间:2020-07-11 21:00:32

标签: python arrays user-interface tkinter draw

最后,

目标要有一块木板(示例尺寸:宽度= 200,高度= 20),而每个“宽度/高度”单位是一个像素在tkinter GUI上。按下像素时,它会保持“标记”状态,使我可以在此板上绘制图片。重要的是,我可以获得已标记/未标记的像素的信息(最好是字节数组,例如11010100,其中“点击”为1,0 “未点击”)。

在这种情况下,“像素”一词可能令人困惑,我不知道如何更好地描述它。我有一个类比(这有点荒谬,但是在这里:“儿童磁性绘图板”是; click here for a google image;在这种情况下,该板是我的tkinter GUI,可以在其中绘制图形,最后在“保存” /完成后,我得到了一个字节数组中的标记像素,最好是从左到右,其中从上到下读取每一列)

我尝试(显然)的Canvas无法正常工作;以及将每个“像素”都设置为按钮(由于各种各样的设置非常适合),尽管tkinter按钮(尤其是100多个)倾向于加载相当长的时间。

//编辑: enter image description here 自绘;制图板应该类似-我需要标记了“像素”的信息,因此我可以将它们放在一个数组中(并可能稍后对其进行重构,依此类推)

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是在画布上创建矩形网格。然后可以通过设置每个矩形的颜色来创建图形。要获取字节数组,可以遍历矩形以获取其颜色。

这是一个快速而肮脏的例子。您可以通过单击并拖动来绘制。当您单击“打印数据”按钮时,它将在正方形为黑色的任何地方打印带有“ 1”的字符串列表。

screenshot

这是按钮的输出:

00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000001000001000000
00000000000000000000
00000000000000000000
00000000000000000000
00001000000000001000
00000100000000010000
00000011111111100000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000

import tkinter as tk

class DrawableGrid(tk.Frame):
    def __init__(self, parent, width, height, size=5):
        super().__init__(parent, bd=1, relief="sunken")
        self.width = width
        self.height = height
        self.size = size
        canvas_width = width*size
        canvas_height = height*size
        self.canvas = tk.Canvas(self, bd=0, highlightthickness=0, width=canvas_width, height=canvas_height)
        self.canvas.pack(fill="both", expand=True, padx=2, pady=2)

        for row in range(self.height):
            for column in range(self.width):
                x0, y0 = (column * size), (row*size)
                x1, y1 = (x0 + size), (y0 + size)
                self.canvas.create_rectangle(x0, y0, x1, y1,
                                             fill="white", outline="gray",
                                             tags=(self._tag(row, column),"cell" ))
        self.canvas.tag_bind("cell", "<B1-Motion>", self.paint)
        self.canvas.tag_bind("cell", "<1>", self.paint)

    def _tag(self, row, column):
        """Return the tag for a given row and column"""
        tag = f"{row},{column}"
        return tag

    def get_pixels(self):
        row = ""
        for row in range(self.height):
            output = ""
            for column in range(self.width):
                color = self.canvas.itemcget(self._tag(row, column), "fill")
                value = "1" if color == "black" else "0"
                output += value
            print(output)

    def paint(self, event):
        cell = self.canvas.find_closest(event.x, event.y)
        self.canvas.itemconfigure(cell, fill="black")


root = tk.Tk()

canvas = DrawableGrid(root, width=20, height=15, size=10)
b = tk.Button(root, text="Print Data", command=canvas.get_pixels)
b.pack(side="top")
canvas.pack(fill="both", expand=True)
root.mainloop()