0

I'm trying to code a GUI with tkinter that displays the latest top 5 news fetched from NewsAPI. Everytime I run it, I get the following error:

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'

What am I doing wrong? Here's my code:

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()
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
dizzy_isi
  • 1
  • 1
  • 1
    the error message is telling you `news` does not have an `articles` key – gold_cy Nov 27 '21 at 12:38
  • What have you tried to debug this? Are you certain that news returns what it should ? Are you certain that `"articels"` exist in `news`? We cant reproduce your issue and therefore it is unlikely to get an answer to this question. – Thingamabobs Nov 27 '21 at 12:39
  • Just print out `news` and see why you got such error. It is basic technique on debugging. – acw1668 Nov 27 '21 at 13:34
  • 1
    You have missed `=` after `apiKey` in `url`, so the request will not get any result. – acw1668 Nov 27 '21 at 14:19

0 Answers0