我正在使用Tkinter模块创建一个本地(Khaleej时报)新闻应用程序。首先,我在Khaleej Times网站上浏览热门新闻,存储在列表中,然后在Tkinter模块的文本小部件中显示
应用程序中有14个新闻列表。但我想为14条新闻列表中的每一条插入链接,以便打开Khaleej Times网站上的特定新闻。为了做到这一点,我需要为14个新闻列表中的每一个创建标签(标签文本:“单击了解更多”)。但是,手动为这14次编写标签小部件代码将非常繁琐。因此,请帮助我如何使用For循环或任何使代码更短的方法
代码如下:
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'])))
上述代码应重复14次
请帮忙。另外,请建议是否有其他WAT来完成它
您可以这样做:
相关问题 更多 >
编程相关推荐