問題的關鍵是,我在下面的代碼片段中做錯了什麼?如何使用tkinter/ttk在Python 3中顯示圖像?
from tkinter import *
from tkinter.ttk import *
root = Tk()
myButton = Button(root)
myImage = PhotoImage(myButton, file='myPicture.gif')
myButton.image = myImage
myButton.configure(image=myImage)
root.mainloop()
的錯誤信息,我從IDLE3得到如下:
>>>
Traceback (most recent call last):
File "/home/bob/Documents/Python/tkImageTest.py", line 9, in <module>
myButton.configure(image=myImage)
File "/usr/lib/python3.2/tkinter/__init__.py", line 1196, in configure
return self._configure('configure', cnf, kw)
File "/usr/lib/python3.2/tkinter/__init__.py", line 1187, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TypeError: __str__ returned non-string (type Button)
>>>
此錯誤消息有我難住了,我根本不明白它是什麼想說的。有任何想法嗎?
我還希望更改建議...
BTW我已經檢查這個參考http://effbot.org/tkinterbook/photoimage.htm - 你會看到我的代碼片段看起來非常相似! – Bobble 2012-07-22 07:24:28
該錯誤似乎指向傳遞給'PhotoImage()'的'myButton'參數。我不相信'PhotoImage()'引用了一個widget對象,所以這可能會導致錯誤。嘗試沒有它的行,如'myImage = PhotoImage(file ='myPicture.gif')' – gary 2012-07-22 18:32:07
@Gary,似乎這樣做。我被一些文檔(以及我產生的一些其他錯誤)誤導爲認爲'PhotoImage'需要明確引用根窗口。經過一些更多的調整後,我發現可以通過'PhotoImage'構造函數的另一個配置選項來提供對根或者按鈕本身的引用,'PhotoImage(master = myButton,file ='myFile.gif')',但是我寫的方式,它看起來像Tkinter的名字,應該是一個字符串,ofc。 – Bobble 2012-07-23 03:09:48