0

我正在尝试使用 tkinter 编写一个 GUI,以显示从 NewsAPI 获取的最新前 5 条新闻。每次我运行它,我都会收到以下错误:

Traceback (most recent call last):
  File "/Users/isabelleschmit/PycharmProjects/Finalproject/News-App.py", line 48, in <module>
    getNews()
  File "/Users/isabelleschmit/PycharmProjects/Finalproject/News-App.py", line 12, in getNews
    articles = news["articles"] #fetching articles as data from the url
KeyError: 'articles'

我究竟做错了什么?这是我的代码:

import requests 
import tkinter as tk #to create a GUI

def getNews():
    api_key = "hidden"
    url = "https://newsapi.org/v2/top-headlines?country=us&apiKey"+api_key
    news=requests.get(url).json() 

    articles = news["articles"] 

    my_articles = []
    my_news = ""

    for article in articles:
        my_articles.append(article["title"]) 

        #creating a loop to show the top 5 articles
        for i in range(5):
            my_news = my_news + str(i+1) + ". " + my_articles[i] + "\n" 


        #print data within the GUI
        label.config(text = my_news)

#define the canvas of the GUI
canvas = tk.Tk()
canvas.geometry("900x600") 
canvas.title("Your latest news") 


button = tk.Button(canvas, font = 25, text = "Update my news", command = getNews)
button.pack(pady = 25) 


label = tk.Label(canvas, font = 20, justify = "left")
label.pack(pady = 25) 

#call the function
getNews()

#create a loop
canvas.mainloop()
4

0 回答 0