微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Tkinter,Canvas 转换/保存细节

如何解决Tkinter,Canvas 转换/保存细节

这是我的问题。我正在尝试将画布转换为图像。首先,我创建画布绘制的附言,然后将其转换为 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()

解决方法

将画布绘图保存到 postscript 文件时,会忽略画布的背景颜色。由于您使用了白色颜色作为油漆颜色,因此输出的图形是白底白字,看起来没有绘制任何内容。

如果您想在输出 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,1000,fill="black")
        ...

下面是您应该如何创建 Paint 类:

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。