Tkinter,Canvas converting/saving 详情

Tkinter,Canvas converting/saving details

这是我的问题。我正在尝试将我的 canvas 画成图像。首先,我创建我的 canvas 画的后记,然后我将它转换成 png。问题是我获得了白色图像 w/o 的变化。 所以,这是我的 class:

class Paint(Frame):
 def __init__(self, parent):
    Frame.__init__(self, parent)
    self.parent = parent
    self.color = "white"
    self.brush_size = 5
    self.setUI()

def draw(self, event):
    self.canv.create_rectangle(event.x - 7, event.y - 7, event.x + 7, event.y + 7,
                          fill=self.color, outline=self.color)

def setUI(self):
    self.pack(fill=BOTH, expand=1)
    self.canv = Canvas(self, bg="black")
    self.columnconfigure(0, weight=1)
    self.rowconfigure(0, weight=1)
    self.canv.grid(padx=5, pady=5, sticky=E + W + S + N)
    self.canv.bind("<B1-Motion>", self.draw)
def clear(self):
    self.canv.delete(ALL)

def save(self):
    self.canv.update()
    self.canv.postscript(file="D:\Новая папка\test.xps", colormode="color")
    im2 = Image.open("D:\Новая папка\test.xps")
    im2.save("D:\Новая папка\test.png", 'png')

我的主要:

root = Tk()
frame=Canvas(root,height=200,width=300)

root.geometry("500x600")
app = Paint(frame)
frame.create_rectangle(10,10,50,50)
frame.pack()
b3= Button(
    text="Apply!",
    width=35,
    height=1,
    bg="white",
    fg="black",
    command=lambda :[which_button("Activated"),b3_clicked(),app.save()],
    font=25
)
b3.pack(side=TOP)
root.mainloop()

当您将 canvas 绘图保存到 postscript 文件时,canvas 的背景颜色将被忽略。由于您使用 white 颜色作为油漆颜色,因此输出的图纸是 white on white,看起来什么也没画。

如果要在输出的 postscript 文件中使用黑色背景,请使用 .create_rectangle(..., fill="black") 将 canvas 填充为黑色。

class Paint(Frame):
    ...
    def setUI(self):
        # better call pack() outside Paint class
        #self.pack(fill=BOTH, expand=1)
        self.canv = Canvas(self)
        # fill the canvas with black color
        # make sure the rectangle is big enough to cover the visible area
        self.canv.create_rectangle(0, 0, 1000, 1000, fill="black")
        ...

以下是您应该如何创建 Paint class:

root = Tk()
root.geometry("500x600")

app = Paint(root)
app.pack(fill=BOTH, expand=1)
...