Jon Jon - 3 months ago 66
Python Question

Change picture when tkinter button clicked

I'm using tkinter in python 3 to produce some buttons and some labels which change colour when the button is clicked (and turn on a GPIO pin on the Rasp pi too)

Is it possible to change the .gif that the button uses when the button is clicked? I want it to say ON when the GPIO pin is off, and OFF when the GPIO pin is on.

At the moment I have:

#BCM17
GPIO.setup(17,GPIO.OUT)
colour17=StringVar()
pinstate17=GPIO.input(17)
if pinstate17==1:
colour17.set('red')
else:
colour17.set('green')

BCM17Bimage=tk.PhotoImage(file='on.gif')
BCM17B = Button(clock, text="GPIO 0\nBCM 17", image=BCM17Bimage, width=78, height=100, bg="grey", command=BCM17f).grid(column=2, row=1)
BCM17L = Label(clock, text="GPIO 0\nBCM 17", font=(fontname,12), fg='white', bg=colour17.get(), width=10, height=2)
BCM17L.grid(column=0, row=1)


And, the def for the button is:

def BCM17f():
pinstate17=GPIO.input(17)
colour17.set('red' if pinstate17==0 else 'green')
BCM17L.configure(bg=colour17.get())
if pinstate17==0:
GPIO.output(17,True)
else:
GPIO.output(17,False)
print(pinstate17)


A random aside too - is it possible to get an email when people reply to a post on here? Had a good look, but cant see an option for it anywhere.

Jon Jon
Answer

Solved it:

#BCM17
GPIO.setup(17,GPIO.OUT)
colour17=StringVar()
pinstate17=GPIO.input(17)
if pinstate17==1:
    colour17.set('red')
else:
    colour17.set('green')
BCM17L = Label(clock, text="GPIO 0\nBCM 17", font=(fontname,12), fg='white', bg=colour17.get(), width=10, height=2)
BCM17L.grid(column=0, row=1)

image17on=tk.PhotoImage(file="on.gif")
image17off=tk.PhotoImage(file="off.gif")

if pinstate17==1:
    image17=image17on
else:
    image17=image17off

BCM17B = Button(clock, text="GPIO 0\nBCM 17",
image=image17,
width=75, height=75, bg="grey",
command=BCM17f)
BCM17B.grid(column=2, row=1)

with def:

def BCM17f():
    pinstate17=GPIO.input(17)
    colour17.set('red' if pinstate17==0 else 'green')
    BCM17L.configure(bg=colour17.get())
    global toggle17
    if toggle17 and pinstate17==1:
        GPIO.output(17,False)
        BCM17B.config(image=image17off)
        toggle17 = not toggle17
    else:
        GPIO.output(17,True)
        BCM17B.config(image=image17on)
        toggle17 = not toggle17