Python 那么,curSongJson是如何定义的呢?
如果我在运行应用程序时在displaySongs函数中定义curSongJson,为什么会说没有定义它?之前我删除了displaySongs功能,只是使用了一个while循环,但我需要tkinter和更新标签的功能Python 那么,curSongJson是如何定义的呢?,python,python-3.x,Python,Python 3.x,如果我在运行应用程序时在displaySongs函数中定义curSongJson,为什么会说没有定义它?之前我删除了displaySongs功能,只是使用了一个while循环,但我需要tkinter和更新标签的功能 import requests import time import tkinter token = '' endpoint = "https://api.spotify.com/v1/me/player/currently-playing" spotifyHe
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()
# imageLabel = tkinter.Label(window)
# imageLabel.pack()
def GrabSpotifyCurSong():
return curSongJson['item']['name']
def GrabSpotifyCurArtist():
return curSongJson['item']['artists'][0]['name']
def GrabCurrentSongImage():
return curSongJson['item']['album']['images'][0]['url']
def displaySongs():
try:
curSong = requests.get(endpoint, headers=spotifyHeaders)
curSongJson = curSong.json()
except:
print("Please start listening to a song")
time.sleep(2)
# with open('CurrentSong.jpg','wb+') as SongImage:
# response = requests.get(GrabCurrentSongImage())
# SongImage.write(response.content)
currentSong = GrabSpotifyCurSong()
currentArtist = GrabSpotifyCurArtist()
# imageLabel['text'] = f'{currentArtist} - {currentSong}'
print(f'{currentArtist} - {currentSong}')
# window.after(4000,displaySongs)
displaySongs()
# window.mainloop()
curSongJson
是一个局部变量,因此它的作用域仅限于定义它的函数。因此,在displaySongs()
方法之外无法访问它
您可以在需要时将currSongJson
作为参数传递给其他函数,如-
导入请求
导入时间
进口tkinter
令牌=“”
端点=”https://api.spotify.com/v1/me/player/currently-playing"
spotifyHeaders={'Authorization':'Bearer'+token}
请求量=1
#window=tkinter.Tk()
#imageLabel=tkinter.Label(窗口)
#imageLabel.pack()
def GrabspottifyCursong(curSongJson):
返回curSongJson['item']['name']
def GrabSpotifyCurArtist(curSongJson):
返回curSongJson['item']['artists'][0]['name']
def GrabCurrentSongImage(curSongJson):
返回curSongJson['item']['album']['images'][0]['url']
def displaySongs():
尝试:
curSong=requests.get(端点,headers=spotifyHeaders)
curSongJson=curSong.json()
除:
打印(“请开始听一首歌”)
时间。睡眠(2)
#以open('CurrentSong.jpg','wb+')作为歌曲图像:
#response=requests.get(GrabCurrentSongImage(curSongJson))
#SongImage.write(响应.内容)
currentSong=grabspottifycursong(curSongJson)
currentArtist=GrabSpotifyCurArtist(curSongJson)
#imageLabel['text']=f'{CurrentArtister}-{currentSong}'
打印(f'{CurrentArtister}-{currentSong}')
#window.after(4000,显示歌曲)
显示歌曲()
#window.mainloop()
如果displaySongs
中的try
块出现异常,则不会定义异常,而且您需要将其作为参数传递给函数,因为它不在其作用域中。我将try块放入while循环中,现在它是这样工作的,我将cursongJson作为参数传递,一切正常。非常感谢。