问题的关键是,我在下面的代码片段中做错了什么?如何使用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