gpt4 book ai didi

python - Tkinter 标签图像设置不起作用

转载 作者:行者123 更新时间:2023-12-02 20:46:04 37 4
gpt4 key购买 nike

我一直在学习如何从头开始使用 Tkinter,同时尝试在框架中设置一个简单的 Label 小部件:

from Tkinter import *
from ttk import *

root = Tk()
root.title("Practice")

mainW = LabelFrame(root, text = "Main info")
mainW.grid()

image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
image.grid(column = 0, row = 0)

codeEntry = Entry(mainW, text = "User Code")
codeEntry.grid(column = 1, row = 0)

root.mainloop()

我收到以下错误:

Traceback (most recent call last):
File "Tutorial.py", line 10, in <module>
image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
File "C:\Python27\lib\lib-tk\ttk.py", line 757, in __init__
Widget.__init__(self, master, "ttk::label", kw)
File "C:\Python27\lib\lib-tk\ttk.py", line 555, in __init__
Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image specification must contain an odd number of elements

我检查了图像格式、路线等。现在我真的不知道是什么给我带来了麻烦。

最佳答案

image
The image to display in the widget. The value should be a PhotoImage, BitmapImage, or a compatible object. If specified, this takes precedence over the text and bitmap options. (image/Image)

现在您只需传递图像选项 label 的字符串。你需要类似的东西,

photo = PhotoImage(file="image.gif")
label = Label(..., image=photo)
label.photo = photo #reference keeping is important when working with images

现在,由于您使用的是PNG图像,因此您需要安装并使用Python Imaging Library (PIL)尽管。欲了解更多信息,您可以阅读Photo Image来自 effbot 的部分。

关于python - Tkinter 标签图像设置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44405989/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com