Cb9867
Cb9867

Reputation: 91

how can i change the button icon in tkinter

i am creating a gui in tkinter in which i have a button. and i don't want a simple button i want an icon instead of a button and when i click on a button its icon should be change. so that i can perform start() and stop() function with a same button.

import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
root = tk.Tk()
def change_i():
        if sound_btn[image] == icon:
            #start_recording()

            sound_btn.config(image=icon2)
        else:
            #stop_recording()

            sound_btn.config(image=icon)

icon = PhotoImage(file='dh.png')
icon2 = PhotoImage(file='stop.png')

sound_btn = tk.Button(frame, image=icon, width=70,height=60,relief=FLAT ,command=change_i )
sound_btn.grid(row=0, column=1)
root.mainloop()

Upvotes: 1

Views: 15531

Answers (1)

Ed Ward
Ed Ward

Reputation: 2331

This works:

import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
root = tk.Tk()
def change_i():
    if sound_btn.image == icon:
        #start_recording()

        sound_btn.config(image=icon2)
        sound_btn.image = icon2
    else:
        #stop_recording()

        sound_btn.config(image=icon)
        sound_btn.image = icon

icon = PhotoImage(file='dh.png')
icon2 = PhotoImage(file='stop.png')

sound_btn = tk.Button(root, image=icon, width=70,height=60,relief=FLAT ,command=change_i )
sound_btn.image = icon
sound_btn.grid(row=0, column=1)
root.mainloop()

Edit:

This answer works by saving the current image in the image attribute of sound_btn, and compares that each time the button is clicked. sound_btn['image'] returns the "image id" of the current image, not a reference to it.

Upvotes: 3

Related Questions