代碼:
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()
我有這段代碼可以獲取一張隨機的狗照片并將其加載到一個視窗以及一個按鈕中。這很好用,但“下一條狗”按鈕實際上并沒有做任何事情,而且狗的照片幾乎從不與視窗匹配。如何為按鈕添加功能,并使狗照片大小保持一致?
uj5u.com熱心網友回復:
您可以將狗影像的獲取放在一個函式中,并在函式內部更新標簽的影像。然后將此功能分配給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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/452611.html
