Changing the Image on a button

odeits odeits at gmail.com
Fri Feb 20 22:20:30 EST 2009


On Feb 17, 7:14 am, John Posner <jjpos... at snet.net> wrote:
>  >> > Try this change:
>  >> >
>  >> >   from: btn.configure(image = None)
>  >> >     to: img1.blank()
>  >> >
>  >>
>  >> This does in fact clear the image out, however it isn't causing the
>  >> text to display... Do i have have to create a new button and swap it
>  >> out?
>
> I knew you were gonna ask that! :-) I haven't worked in this area before,
> but I
> found this athttp://effbot.org/tkinterbook/button.htm:
>
>     In earlier versions of Tkinter, the image option overrides the text
> option.
>     If you specify both, only the image is displayed. In later versions, you
> can
>     use the compound option to change this behavior. To display text on top
> of
>     an image, set compound to CENTER:
>
>      b = Button(master, text="Click me", image=pattern, compound=CENTER)
>
> So here's a reworking, in which the text and image are both toggled by
> pressing the button:
>
> ### button that toggles both text and image
> from Tkinter import *
>
> def pushed():
>     """callback: button push"""
>
>     global toggle
>
>     if toggle:
>         btn.config(text="", image=img_empty)
>         toggle = not toggle
>     else:
>         btn.config(text=msg, image=img_good)
>         toggle = not toggle
>
> ### main program
> toggle = True
> msg = "hello"
>
> root = Tk()
>
> ### store two versions of an image in global variables:
> # 1. original image
> img_good = PhotoImage(file="bacon.gif")
>
> # 2. blank image, created by copying and erasing
> img_empty = img_good.copy()
> img_empty.blank()
>
> ### create toggle button
> btn = Button(root, compound=CENTER,
>             text="hello", font="helvetica 14 bold",
>             image=img_good,
>             command=pushed)
> btn.pack()
>
> ### go
> root.mainloop()
>
> E-mail message checked by Spyware Doctor (6.0.0.386)
> Database version: 5.11780http://www.pctools.com/en/spyware-doctor-antivirus/

Thank you very much for your help! It is now behaving the way I wanted!



More information about the Python-list mailing list