'Strange bug when cycling dog photos

I have this code that generates a dog photo and can cycle through them.

import tkinter, urllib.request, json, io
from PIL import Image, ImageTk

main = tkinter.Tk()
main.geometry('550x600+800+300')

urllist = []

doglist = []
dognumber = -1

W, H = 500, 460

def resize_image(img):
    ratio = min(W/img.width, H/img.height)
    return img.resize((int(img.width*ratio), int(img.height*ratio)), Image.ANTIALIAS)

def last_image():
    global doglist, dognumber
    dognumber -= 1
    if dognumber < 0:
        dognumber = 0
    l.config(image=doglist[dognumber])

def fetch_image():
    global doglist, dognumber, urllist
    try:
        dognumber += 1
        l.config(image=doglist[dognumber])
    except IndexError:
        dognumber -= 1
        dogapi = urllib.request.urlopen(f'https://dog.ceo/api/breeds/image/random')
        dogjson = dogapi.read()
        dogdict = json.loads(dogjson)
        url = dogdict['message']
        m = urllib.request.urlopen(url)
        mpi = resize_image(Image.open(m))
        tkimg = ImageTk.PhotoImage(mpi)
        doglist.append(tkimg)
        urllist.append(url)
        dognumber += 1
        l.config(image=tkimg)
        l.image = tkimg

def save_dogs():
    global urllist
    w = open('/'.join(__file__.split("\\")[:-1]) + '/doglist.txt', 'w')
    w.write('\n'.join(urllist))

l = tkinter.Label(main, image=tkinter.PhotoImage(), width=W, height=H)
b = tkinter.Button(main, text='Next Dog', command=fetch_image)
b2 = tkinter.Button(main, text='Last Dog', command=last_image)
b3 = tkinter.Button(main, text='Save Dogs', command=save_dogs)

for _ in range(10):
    fetch_image()

dognumber = -1

l.pack()
b.pack()
b2.pack()
b3.pack()

main.mainloop()

It works fine, except for when it generates the first 10 photos. For some reason, the "Last Dog" button works the first time even though dognumber is reset to -1, and then when you hit "Next Dog" again it shows you a completely different photo. Why is this happening?

I've tried messing with what the dognumber variable starts has, expecting to make it start on the first element, and (somewhat unsurprisingly) nothing different happened.



Solution 1:[1]

It was showing the last image generated, because it changes image config every time, hitting last dog just updated it. Pretty simple solution but it took a while to figure out...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Picklas