我对 Python 编程和使用许多可用的 Python 库非常缺乏经验。我希望能够将图像/标签放置在 Tkinter 窗口上的某个位置。我一直在寻找有关如何实现这一目标的信息,到目前为止还没有运气。我非常感谢任何帮助或提示来帮助我进行 Python 冒险。预先感谢。
到目前为止,我已经学会了如何使用 Pillow 打开 .png 文件并调整其大小。我希望这可以引导我学习如何将其编写到我已经创建的 GUI 窗口中,并按照我的计划和预期工作。这真的让我感觉像纽比。再次提前致谢。
要在 tkinter 小部件上插入图像,您必须首先创建一个 tkimage,然后将其放在您想要放置的位置。
import tkinter
root = tkinter.Tk()
path_image = './src/frutas/umbu.png'
tkimage = tkinter.PhotoImage(master=root, file=path_image)
您可以使用
.zoom()
或 .subsample()
调整图像尺寸。
示例:
tkimage_smaller = tkimage.subsample(2)
不推荐。最好获取适当尺寸的图像(可以保持质量)。
要在标签或按钮上插入图像,请执行以下操作:
# If you want just the image
label = tkinter.Label(master=root, image=tkimage)
# If you want text and image
# compound ajust the image on widget region, left side in that case
button = tkinter.Button(master=root, text='Bem docinha kak', image=tkimage, compound=tkinter.LEFT)
不幸的是 tkinter 不支持透明度,因此标签或按钮会在 png 图像上放置背景。
如果您想要透明度,请使用 Canvas。
canvas = tkinter.Canvas(master=root)
canvas.place(x=0, y=0, widht=500, height=500)
id_image = canvas.create_image((10, 10), image=tkimage)
# If you want to move around the image
canvas.itemconfigure(id_image, 10, 10)