gpt4 book ai didi

image - 如何使用 tkinter/ttk 在 Python 3 中显示图像?

转载 作者:行者123 更新时间:2023-12-04 18:47:39 24 4
gpt4 key购买 nike

问题的关键是,我在下面的代码片段中做错了什么?

    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)
>>>

这个错误信息让我难住了,我根本不明白它想说什么。有任何想法吗?

我也很感激有关更改的建议...

最佳答案

该错误似乎指向 myButton参数传递给 PhotoImage .正如您在评论中指出的那样,PhotoImage将小部件对象视为字符串(有几个字符串类型的选项;请参阅 PhotoImage 选项列表 here)。

如果您在不引用 myButton 的情况下实现该行,您的代码将起作用目的:

myImage = PhotoImage(file='myPicture.gif')

我不确定您是否需要更改 PhotoImage构造函数。看 PhotoImage docs 以确定该类的有效选项(即资源名称)。引用帮助文件:

Help on class PhotoImage in module tkinter:

class PhotoImage(Image)

| Widget which can display colored images in GIF, PPM/PGM format.
|
| Method resolution order:
| PhotoImage
| Image
| builtins.object
|
| Methods defined here:
|
| __getitem__(self, key)
| # XXX config
|
| __init__(self, name=None, cnf={}, master=None, **kw)
| Create an image with NAME.
|
| Valid resource names: data, format, file, gamma, height, palette,
| width.


仅供引用:从 Python 在命令行或从 IDLE 获取文档的最简单方法:
from tkinter import PhotoImage
help(PhotoImage)

最后,关于这个类(class)的另一个有用的链接是 http://tkinter.unpythonic.net/wiki/PhotoImage .

关于image - 如何使用 tkinter/ttk 在 Python 3 中显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11598360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com