尝试使用 PIL 保存 tkinter 画布时,当画布背景设置为
"white"
并将创建的线条的填充选项设置为 "black"
时,它会按预期工作,但是当将画布背景设置为 "black"
且填充参数时,它会按预期工作创建的线条到"white"
,保存的图像将只是纯色(白色)。为什么会出现这种情况?
Python 3.11.8
枕头==10.2.0
import tkinter as tk
import io
from PIL import Image
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.line_start = None
self.canvas = tk.Canvas(self, width=300, height=300, bg="white")
self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y))
self.button = tk.Button(self, text="save", command=self.save)
self.canvas.pack(fill="both", expand=True)
self.canvas.focus_set()
self.button.pack(pady=10)
def draw(self, x, y):
if self.line_start:
x_origin, y_origin = self.line_start
self.canvas.create_line(x_origin, y_origin, x, y, fill="black")
self.line_start = x, y
def save(self):
ps = self.canvas.postscript(colormode="color")
img = Image.open(io.BytesIO(ps.encode("utf-8")))
img.save("working.png")
app = App()
app.mainloop()
import tkinter as tk
import io
from PIL import Image
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.line_start = None
self.canvas = tk.Canvas(self, width=300, height=300, bg="black")
self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y))
self.button = tk.Button(self, text="save", command=self.save)
self.canvas.pack(fill="both", expand=True)
self.canvas.focus_set()
self.button.pack(pady=10)
def draw(self, x, y):
if self.line_start:
x_origin, y_origin = self.line_start
self.canvas.create_line(x_origin, y_origin, x, y, fill="white")
self.line_start = x, y
def save(self):
ps = self.canvas.postscript(colormode="color")
img = Image.open(io.BytesIO(ps.encode("utf-8")))
img.save("white.png")
app = App()
app.mainloop()
本文内容可能适用于您。
画布背景颜色未保存
我不相信
命令旨在保留画布小部件的背景颜色。它只保存画布上出现的项目。postscript
一个简单的解决方案是绘制一个与画布大小完全相同的矩形,然后更改该矩形的颜色。
因此,您只需将以下行添加到问题中的保存全白图像的源中。
self.canvas = tk.Canvas(self, width=300, height=300, bg="black")
self.canvas.create_rectangle(0, 0, 300, 300, fill='black') #### added this line
self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y))