BiRD
BiRD

Reputation: 134

Image not showing tkinter

I created a switch button but the image "mid.png" is not showing. Here is my code

from tkinter import *

window=Tk()

def switch_button():
    global btn_state
    btn_state=1

    def test(event):
        global btn_state
        if btn_state == 1:
            win_btn.config(image=mid_btn)
            window.after(100,None)
            win_btn.config(image=on_btn)
            btn_state=0
        else:
            win_btn.config(image=mid_btn)
            window.after(100,None)
            win_btn.config(image=off_btn)
            btn_state=1

    on_btn=PhotoImage(file='on.png')
    mid_btn=PhotoImage(file='mid.png')
    off_btn=PhotoImage(file='off.png')

    win_btn = Label(window, image=off_btn)
    win_btn.bind("<Button-1>",test)
    win_btn.pack()
    
switch_button()

window.geometry("400x500")
window.mainloop()

I'm trying to show "mid.png" before it switches to "on.png" or "off.png" so the switch can be more smooth

Upvotes: 1

Views: 95

Answers (1)

acw1668
acw1668

Reputation: 47173

You need to add win_btn.update_idletasks() before calling window.after(100, None).

However I suggest to use after() to schedule the change of image instead of using it just like sleep().

Below is a modified switch_button():

def switch_button():
    def test(event):
        btn_state = win_btn['image'] # get the current image variable name
        win_btn.config(image=mid_btn) # change to 'mid' state
        # schedule to change to target state 100ms later
        window.after(100, win_btn.config, {'image': off_btn if btn_state == 'ON' else on_btn})

    on_btn = PhotoImage(file='on.png', name='ON') # set image variable name to ON
    mid_btn = PhotoImage(file='mid.png')
    off_btn = PhotoImage(file='off.png', name='OFF') # set image variable name to OFF

    win_btn = Label(window, image=off_btn)
    win_btn.bind("<Button-1>", test)
    win_btn.pack()

Upvotes: 2

Related Questions