【问题标题】:Tkinter,Canvas converting/saving detailsTkinter,Canvas 转换/保存细节
【发布时间】:2021-07-07 15:24:18
【问题描述】:

这是我的问题。我正在尝试将画布绘制成图像。首先,我创建了画布的后记,然后将其转换为 png。问题是我获得了没有变化的白色图像。 所以,有我的课:

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()

【问题讨论】:

  • 为什么要在画布内的框架内创建画布?如果主人是画布,你不应该使用.pack。这是不好的做法。

标签: python tkinter tkinter-canvas


【解决方案1】:

当您将画布绘图保存到 postscript 文件时,画布的背景颜色将被忽略。由于您已使用 white 颜色作为油漆颜色,因此输出绘图是 white on white,看起来像没有绘制任何内容。

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

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 类:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 2019-04-16
    • 2013-05-12
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多