2017-06-07 31 views
0

我一直在學習如何從頭開始使用Tkinter的,雖然我嘗試設置一個簡單的標籤控件在一個框架:Tkinter的標籤圖像設置不需額外工作

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 

我檢查了圖像格式,路線等。現在我不知道什麼會導致我麻煩。

回答

1

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)雖然。欲瞭解更多信息,您可以閱讀effbot的Photo Image部分。