Changing the Image on a button

John Posner jjposner at snet.net
Tue Feb 17 16:14:06 CET 2009


 >> > 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 at http://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.11780
http://www.pctools.com/en/spyware-doctor-antivirus/



More information about the Python-list mailing list