Tkinter 标签图像设置不起作用

of.*_*z10 2 python label tkinter python-2.7

我一直在学习如何从头开始使用 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()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

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

Laf*_*los 5

image
要在小部件中显示的图像。该值应该是 PhotoImage、BitmapImage 或兼容对象。如果指定,它将优先于文本和位图选项。(图片/图片)

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

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

现在,由于您使用的是 PNG 图像,因此您需要安装并使用Python 图像库 (PIL)。有关更多信息,您可以阅读effbot 的照片图像部分。