当前,我正在使用此代码段,这似乎很简单:
label = ttk.Label(mainframe)
image1 = PhotoImage(file='my_image.gif')
label['image'] = image1
label.grid(column=1, row=0)
但是,如果我在photoshop中编辑my_image.gif的大小,然后再次运行,图像将被拉伸到相同的大小,无论我将基础图像缩小多小,这种情况似乎都会继续。在我看来,这似乎暗示PhotoImage或它上面的内容会强制使用默认大小或特定的最小大小。我找不到任何文档可以证明是这种情况。
从here中,我找到了我使用的help(PhotoImage)建议。在python解释器中,我运行help(PhotoImage)命令,发现了这一点:
height(self)
Return the height of the image.
type(self)
Return the type of the imgage, e.g. "photo" or "bitmap".
width(self)
Return the width of the image.
但是它似乎也无法为我提供任何类型的图像尺寸。
经过全面搜索,根本看不到参考文献之后,我开始怀疑在Label中使用图像是出于特定目的,而我正在错误地解决所有问题。我想做的就是在窗口顶部放置一个徽标,但我希望徽标的大小受到限制,以便不占据整个窗口。
还值得注意的是this question,它似乎缺少答案,但是我也很好奇上面是否有一些文档。也许我缺少明显的东西,但是我确实检查了python文档和http://www.tkdocs.com网站以获取更多信息。
显然我犯了一个错误,但是我不知道那是什么。最后,这段代码为我做到了:
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("ImageTest")
label = ttk.Label(root)
image1 = PhotoImage(file='my_image.gif')
label['image'] = image1
label.grid(column=1, row=0)
root.mainloop()
现在都按预期工作。