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

Bob*_*ble 5 image tkinter button ttk python-3.x

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

    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()
Run Code Online (Sandbox Code Playgroud)

我从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)
    >>> 
Run Code Online (Sandbox Code Playgroud)

这个错误信息让我难过,我根本不明白它想说的是什么.有任何想法吗?

我也很感激改变的建议......

gar*_*ary 7

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

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

myImage = PhotoImage(file='myPicture.gif')
Run Code Online (Sandbox Code Playgroud)

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

模块tkinter中的类PhotoImage帮助:

class PhotoImage(图片仅供参考)

| 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.
Run Code Online (Sandbox Code Playgroud)

仅供参考:在命令行或IDLE从Python获取文档的最简单方法:

from tkinter import PhotoImage
help(PhotoImage)
Run Code Online (Sandbox Code Playgroud)

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