Albain Albain - 3 months ago 10
Python Question

Update image of a button depending on its previous image

I am trying to program a start/pause button in Tkinter (Pyhton) but the following code doesn't work:

def startpause():
if startpause_button.cget('image')=='start_image':
startpause_button.config(image=pause_image)
else:
startpause_button.config(image=start_image)
return

start_image=ImageTk.PhotoImage(file='start.png')
pause_image=ImageTk.PhotoImage(file='pause.png')

startpause_button=ttk.Button(frame,image=start_image,command = startpause)


I understand the issue is about cget (which return ('pyimage3'), ) and what it returns but I don't know what to put as a value to check ("('pyimage3')," doesn't work).

Do you have any idea about this issue?

Thank you.

Answer

startpause_button.cget('image') and 'start_image' are two different things, .cget('image') returns the name of the image in a list e.g. ('pyimage1',). This means to compare them you need to take it out of the list with [0] and make sure both variables are strings with str() because 'pyimage1' and pyimage1 are also two different things

import tkinter.ttk
from tkinter import Tk, PhotoImage

def startpause():
    global start_image
    if str(startpause_button.cget('image')[0])==str(start_image):
        startpause_button.config(image=pause_image)
    else:
        startpause_button.config(image=start_image)
    #return # i dont think you need this

global start_image
start_image=PhotoImage(file='start.gif')
pause_image=PhotoImage(file='pause.gif')

startpause_button=tkinter.ttk.Button(frame,image=start_image,command = startpause)

This does work and I've tested it, hope this helps you! :)