【发布时间】:2023-03-09 14:31:01
【问题描述】:
问题的关键是,我在下面的代码 sn-p 中做错了什么?
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)
>>>
这个错误信息让我很困惑,我根本不明白它想说什么。有什么想法吗?
我也希望能提出更改建议...
【问题讨论】:
-
顺便说一句,我已经检查了这个参考effbot.org/tkinterbook/photoimage.htm - 你会看到我的代码 sn-p 看起来非常相似!
-
错误似乎指向传递给
PhotoImage()的myButton参数。我不相信PhotoImage()引用了一个小部件对象,所以这可能会导致错误。在没有它的情况下尝试该行,例如myImage = PhotoImage(file='myPicture.gif') -
@Gary,这似乎可以做到。我被一些文档(以及我生成的其他一些错误)误导为认为
PhotoImage需要明确引用根窗口。经过更多的摆弄后,我发现对根目录或按钮本身的引用可以由PhotoImage构造函数上的另一个配置选项提供,就像这样,PhotoImage(master=myButton, file='myFile.gif'),但是我编写它的方式,它看起来像 Tkinter name,应该是一个字符串,ofc。 -
知道了。将我的评论变成了答案,并添加了一些其他有用的信息。
标签: image button python-3.x tkinter ttk