为什么这不显示当前歌曲图像?

时间:2021-06-05 02:45:43

标签: python python-3.x tkinter

我试图从歌曲专辑中获取图像以显示在带有歌曲标题和艺术家的窗口中,但它什么也没做。我试过用

替换“imageLabel”

"imageLabel = tkinter.Label(window,image=tkinter.PhotoImage(file="CurrentSong.jpg"))" 但还是不行。

import requests
import time
import tkinter

token = ''
endpoint = "https://api.spotify.com/v1/me/player/currently-playing"
spotifyHeaders = {'Authorization':'Bearer ' + token}
requestAmount = 1
window = tkinter.Tk(className="|CurrentSong Spotify Song|")
window.geometry('400x400')
canvas = tkinter.Canvas(window,height=1000,width=1000)
canvas.pack()
songLabel = tkinter.Label(window,bg='grey')
songLabel.pack()


def GrabSpotifyCurSong(curSongJson):
    return curSongJson['item']['name']
def GrabSpotifyCurArtist(curSongJson):
    return curSongJson['item']['artists'][0]['name']
def GrabCurrentSongImage(curSongJson):
    return curSongJson['item']['album']['images'][0]['url']
    
def displaySongs():
    while True:
        try:
            curSong = requests.get(endpoint, headers=spotifyHeaders)
            curSongJson = curSong.json()
            break
        except:
            print("Please start listening to a song")
            time.sleep(2)
    with open('CurrentSong.png','wb+') as SongImage:
        response = requests.get(GrabCurrentSongImage(curSongJson))
        SongImage.write(response.content)
    currentSong = GrabSpotifyCurSong(curSongJson)
    currentArtist = GrabSpotifyCurArtist(curSongJson)
    img = tkinter.PhotoImage(file="CurrentSong.png")
    imageLabel = tkinter.Label(window,image=img)
    # songLabel['text'] = f'{currentArtist} - {currentSong}'
    # songLabel.place(height=400,width=400)
    print(f'{currentArtist} - {currentSong}')
    window.after(2500,displaySongs)

displaySongs()
window.mainloop()

1 个答案:

答案 0 :(得分:1)

带有 tkinter 的图像必须是 PhotoImage 实例,这里它只是图像位置的字符串,tkinter 不理解这一点。此外,tkinter.PhotoImage 无法识别 JPEG 格式,因此您必须将其转换为 PNG 或使用 PIL.ImageTk.PhotoImage 才能使用 JPEG。

  • 也适用于 JPEG 和其他格式:

    首先pip install Pillow,然后:

    import tkinter
    from PIL import Image, ImageTk
    
    ....
    img = ImageTk.PhotoImage(Image.open("CurrentSong.jpg"))
    imageLabel = tkinter.Label(window,image=img)
    

    在此处进一步添加,您也可以使用 ImageTk.PhotoImage(file="CurrentSong.jpg") 但这将消除您在想要调整图像大小或对图像进行一些过滤时可以获得的灵活性。如果没有,那就用那个。

  • 对于 GIF、PGM、PPM 和 PNG:

    img = tkinter.PhotoImage(file="CurrentSong.png")
    imageLabel = tkinter.Label(window,image=img)
    

另请注意,如果这些在函数内部,您必须保持对对象的引用,以避免在函数完成运行后被 gc 收集。

相关问题