put a image in a Button in TK??

Eric Brunel eric.brunel at pragmadev.com
Fri Dec 13 03:46:11 EST 2002


jubafre at brturbo.com wrote:
> How can I put a image in button componnent in TK???
> 
> self.button=Button(frame, width=2, image=???????)
> self.button.pack(side=LEFT, pady=5)

self.image = PhotoImage(file='foo.gif')
self.button = Button(frame, image=self.image)

Better not to specify an explicit width or your image may be truncated.

And do put the instance of PhotoImage in an attribute. The button does not 
keep a reference on its image, so if you do something like:

img = PhotoImage(file='foo.gif')
self.button = Button(frame, image=img)
img = None

the image won't show at all: the first line sets one reference on the image 
(the instance of PhotoImage), the second line doesn't add any, and the 
third line loses the reference => the image is garbage collected.

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list