python tkinter ttk,我怎样才能使用的Tkinter / TTK显示在Python 3的图像?

The nub of the matter is, what am I doing wrong in the following code snippet?

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

The error message I get from idle3 is as follows:

>>>

Traceback (most recent call last):

File "/home/bob/Documents/Python/tkImageTest.py", line 9, in

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)

>>>

This error message has me stumped, I simply don't understand what it is trying to say. Any ideas?

I would also appreciate suggestions for changes...

解决方案

The error seems to point to the myButton argument passed to PhotoImage. As you noted in your comment, PhotoImage was treating the widget object as a string (there are several options of type string; see a list of PhotoImage options here).

Your code will work if you implement that line without referencing the myButton object:

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

I'm not certain you need to alter the PhotoImage constructor. Look at the PhotoImage docs to determine the valid options (i.e. resource names) for that class. Quoting the help file:

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.

FYI: The easiest way to get to the docs from Python at the command line or from IDLE:

from tkinter import PhotoImage

help(PhotoImage)

And lastly, another useful link about this class is at http://tkinter.unpythonic.net/wiki/PhotoImage.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值