-
Notifications
You must be signed in to change notification settings - Fork 0
/
news_gui.py
113 lines (93 loc) · 3.1 KB
/
news_gui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import io
import webbrowser
import requests
from tkinter import *
from urllib.request import urlopen
from PIL import ImageTk, Image
class NewsAPP:
def __init__(self):
# Fetch Data
self.data = requests.get(
"https://newsapi.org/v2/top-headlines?country=us&apiKey=61069f0c8a654c839bc560e1a1b463cf"
).json()
# initial GUI
self.load_gui()
# Load first news item
self.load_news_item(0)
def load_gui(self):
self.root = Tk()
self.root.geometry("350x600")
self.root.resizable(0,0)
self.root.title('News App')
self.root.configure(background="black")
def clear(self):
for i in self.root.pack_slaves():
i.destroy()
def load_news_item(self,index):
# clear screen for the new news item
self.clear()
# Image
try:
img_url = self.data["articles"][index] ["urlToImage"]
raw_data = urlopen(img_url).read()
im = Image.open(io.BytesIO(raw_data)).resize ((350, 250))
photo = ImageTk.PhotoImage(im)
except:
img_url = 'https://www.hhireb.com/wp-content/uploads/2019/08/default-no-img.jpg'
raw_data = urlopen(img_url).read()
im = Image.open(io.BytesIO(raw_data)).resize ((350, 250))
photo = ImageTk.PhotoImage(im)
label = Label(self.root, image=photo)
label.pack()
heading = Label(
self.root,
text=self.data["articles"][index]["title"],
bg="black",
fg="white",
wraplength=350,
justify="center",
)
heading.pack(pady=(10, 20))
heading.config(font=("verdana", 15))
details = Label(
self.root,
text=self.data["articles"][index]["description"],
bg="black",
fg="white",
wraplength=350,
justify="center",
)
details.pack(pady=(2, 20))
details.config(font=("verdana", 12))
frame = Frame(self.root, bg="black")
frame.pack(expand=True, fill=BOTH)
if index != 0:
prev = Button(
frame,
text="prev",
width=16,
height=3,
command=lambda: self.load_news_item(index - 1),
)
prev.pack(side=LEFT)
read = Button(
frame,
text="Read More",
width=16,
height=3,
command=lambda url=self.data["articles"][index]["url"]: self.open_link(url),
)
read.pack(side=LEFT)
if index != len(self.data["articles"]) - 1:
next = Button(
frame,
text="Next",
width=16,
height=3,
command=lambda: self.load_news_item(index + 1),
)
next.pack(side=LEFT)
self.root.mainloop()
def open_link(self, url):
webbrowser.open(url)
obj = NewsAPP()