I am creating a Local (Khaleej Times) News App using Tkinter Module. Firstly, I Webscrape Top News in Khaleej Times Website ,store in list and then display in Text Widget from Tkinter Module.
There are 14 news lists in the app. But I want to insert Links for each of the 14 news list in order to open Khaleej Times website of that specific news. In order to do this i need to create label (Label Text:"Click To Know More") for each of the 14 news lists. But it will be tedious to manually write Label widget code for this 14 times. So please help me how we can use For Loop or any ways to make the code shorter.
Here is the code:
from tkinter import *
import requests
from bs4 import BeautifulSoup
import webbrowser
def window():
root1 = Tk()
root1.geometry("520x800")
root1.title("Khaleej Times Top News")
scroll_bar = Scrollbar(root1)
scroll_bar.pack (side = RIGHT, fill = Y)
T = Text(root1, height = 500, width = 250,yscrollcommand=scroll_bar.set)
scroll_bar.config(command = T.yview)
l = Label(root1,text= "Top News")
l.config(font =("Courier", 14))
l.pack()
url="https://www.khaleejtimes.com/?_refresh=true"
r=requests.get(url)
soup=BeautifulSoup(r.content, 'html5lib')
# extracting top and latest news
tab=soup.find('div', attrs = {'class' : 'tab-content'})
newslist = []
topnews = tab.find_all('div', attrs = {'class':"top_news_tab_1"})
for segment in topnews :
news={}
news['category'] = (segment.h4.text.replace("\n", ""). replace(" ",""))
news['url'] = segment.p.a['href']
news['content'] = segment.p.text
newslist.append(news)
for newlist in newslist:
T.insert(END,newlist['category'])
T.insert(END,("\n"))
T.insert(END,newlist['content'])
T.insert(END,("\n"))
T.insert(END,("\n"))
T.insert(END,("\n"))
T.pack(side = LEFT,fill = BOTH)
def callback(url):
webbrowser.open_new(url)
link1 = Label(root1, text="Click To Know More", fg="blue", cursor="hand2", font = ("Courier",10))
link1.place(x=0,y=50)
link1.bind("<Button-1>", lambda e: callback("https://www.khaleejtimes.com/" + str(newslist[0]['url'])))
window()
link1 = Label(root1, text="Click To Know More", fg="blue", cursor="hand2", font = ("Courier",10))
link1.place(x=0,y=50)
link1.bind("<Button-1>", lambda e: callback("https://www.khaleejtimes.com/" + str(newslist[0]['url'])))
The above code should be repeated 14 times.
Kindly Help on this. Also please suggest is there any other wats to accomplish it.