刷新 tkinter window

Refreshing a tkinter window

代码:

import tkinter, urllib.request, json, io
from PIL import Image, ImageTk
main = tkinter.Tk()
main.geometry('500x500+800+300')
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)
mp = io.BytesIO(m.read())
mpi = Image.open(mp)
tkimg = ImageTk.PhotoImage(mpi)
l = tkinter.Label(main, image=tkimg)
b = tkinter.Button(main, text='Next Dog', command='do something to refresh the dog photo')
l.pack()
main.mainloop()

我有这段代码可以随机获取狗的照片并将其加载到 window 以及一个按钮中。 这工作正常,但“下一张狗”按钮实际上没有做任何事情,而且狗的照片几乎从不与 window 匹配。如何为按钮添加功能,并使狗照片大小一致?

你可以把狗图片的获取放在一个函数里,在函数里面更新标签的图片。然后将此功能分配给按钮的 command 选项。

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

main = tkinter.Tk()
main.geometry('500x500+800+300')

# maximum size of image
W, H = 500, 460

# resize image but keeping the aspect ratio
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 fetch_image():
    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)
    l.config(image=tkimg) # show the image
    l.image = tkimg # save a reference of the image to avoid garbage collection

# label to show the image
l = tkinter.Label(main, image=tkinter.PhotoImage(), width=W, height=H)
b = tkinter.Button(main, text='Next Dog', command=fetch_image)

l.pack()
b.pack()

fetch_image() # fetch first image
main.mainloop()