python - 将 python 海龟 Canvas 转换为位图时如何保持 Canvas 大小

标签 python canvas tkinter bitmap

我想将 Python Turtle 模块 (tkinter) Canvas 转换为位图。我按照“How to convert a Python tkinter canvas postscript file to an image file readable by the PIL?”的建议先将其转换为postscript;然后我将其作为 PIL 图像打开,然后将其另存为位图。但位图的大小与原始 Canvas 的大小不同。

import turtle
import io
from PIL import Image

myttl = turtle.Turtle()

wd=500
ht=500
turtle.setup(width=wd, height=ht, startx=0, starty=0)    
turtle.mode('logo')        # start pointing north
myttl.forward(100)

screen = turtle.Screen()
cv = screen.getcanvas()
ps = cv.postscript(colormode='mono')
img = Image.open(io.BytesIO(ps.encode('utf-8'))).convert(mode='1')
img.save('test.bmp')

在上面的代码中, Canvas 是500x500。但文件 test.bmp 缩小为 374x374,并且其图像比屏幕上的海龟图形小。如何获得未缩小的 500x500 位图?

最佳答案

如果我们从分析 postscript 内容开始,我们会发现它对 Canvas 的尺寸进行了 0.7498 的缩放

%%Page: 1 1
save
306.0 396.0 translate
0.7498 0.7498 scale
3 -241 translate
-244 483 moveto 239 483 lineto 239 0 lineto -244 0 lineto closepath clip newpath
gsave
grestore
gsave
0 239 moveto
0 339 lineto
1 setlinecap
1 setlinejoin
1 setlinewidth
[] 0 setdash
0.000 0.000 0.000 setrgbcolor AdjustColor
stroke
grestore
gsave
grestore
gsave
0 339 moveto
-5 330 lineto
0 332 lineto
5 330 lineto
0 339 lineto
0.000 0.000 0.000 setrgbcolor AdjustColor
eofill
0 339 moveto
-5 330 lineto
0 332 lineto
5 330 lineto
0 339 lineto
1 setlinejoin 1 setlinecap
1 setlinewidth
[] 0 setdash
0.000 0.000 0.000 setrgbcolor AdjustColor
stroke
grestore
restore showpage

在对 postscript 进行一些挖掘之后,我发现了关于从 tkinter 的 Canvas 进行 postscript 转换的 perl/Tk 引用指南 here

您实际上可以做的不仅是设置颜色模式,还可以设置页宽/页高。这导致以下行被更改为

ps = cv.postscript(colormode='mono')

ps = cv.postscript(colormode='mono', pagewidth=wd-1, pageheight=ht-1)

结果:

enter image description here

如果您有任何问题,请随时发表评论,我会尽力回复!

附注:

不要问我关于 -1 部分的问题,它不会给我除 501x501 像素以外的任何内容,因此我对此进行了补偿。我不知道为什么它仍然不起作用。

关于python - 将 python 海龟 Canvas 转换为位图时如何保持 Canvas 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51742871/

相关文章:

javascript - 将 ajax arraybuffer 响应绘制到 Canvas 中

javascript - 退格时从输入文本动态增加字体大小

python - 如何将照片插入 Tkinter 窗口,没有 PIL 的枕头

python - 编译 tkinter 游戏

Python,Tkinter,如何根据按钮单击更改GUI

python - Python 脚本中 __name__ 的不同可能值是什么,它们的含义是什么?

python - 检查另一个列表中的字符串列表中是否存在字符串字符?

python numba : how to slice a column from a numpy array?

python - 如何在我的ros系统中添加sensor_msgs.msg类型?

android - Facebook Unity SDK Invitable_friends API 问题