嗨,我正在使用Feedparser获取rss新闻并显示新闻标题
import feedparser
import kivy
kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
def build(self):
d=feedparser.parse('https://en.wikinews.org/w/index.php?title=Special:NewsFeed&feed=rss&categories=Published¬categories=No%20publish%7CArchived%7cAutoArchived%7cdisputed&namespace=0&count=15&ordermethod=categoryadd&stablepages=only')
print (len(d['entries']))
for post in d['entries']:
news=post.title
print(news)
return Label(text=news)
if __name__ == '__main__':
MyApp().run()
即news=post.title
使用猕猴桃标签。
最初的输出如下:
Study suggests Mars hosted life-sustaining habitat for millions of years
NASA's TESS spacecraft reports its first exoplanet
Russians protest against pension reform
US rapper Mac Miller dies at home in Los Angeles
Creativity celebrated at Fan Expo Canada 2018 in Toronto
Brisbane, Australia Magistrates Court charges two cotton farmers with $20m fraud
Fossil genome shows hybrid of two extinct species of human
Singer Aretha Franklin, 'queen of soul', dies aged 76
New South Wales, Australia government says entire state in winter 2018 drought
Real Madrid agrees with Chelsea FC to sign goalkeeper Thibaut Courtois
但是,每当我运行该程序时,Kivy应用程序只会在循环中显示最后一个标题
即:Real Madrid agrees with Chelsea FC to sign goalkeeper Thibaut Courtois
关于我缺少什么的任何想法?任何帮助将不胜感激。
答案 0 :(得分:0)
问题很简单,news
在循环中被覆盖,因此它采用了最后一个值,一种可能的解决方案是将文本连接起来:
import feedparser
import kivy
kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
def build(self):
url = 'https://en.wikinews.org/w/index.php?title=Special:NewsFeed&feed=rss&categories=Published¬categories=No%20publish%7CArchived%7cAutoArchived%7cdisputed&namespace=0&count=15&ordermethod=categoryadd&stablepages=only'
d=feedparser.parse(url)
news = ""
for post in d['entries']:
news += post.title + "\n"
return Label(text=news)
if __name__ == '__main__':
MyApp().run()
另一种选择是使用BoxLayout
并创建多个Label
:
import feedparser
import kivy
kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
class MyApp(App):
def build(self):
root = BoxLayout(orientation='vertical')
url = 'https://en.wikinews.org/w/index.php?title=Special:NewsFeed&feed=rss&categories=Published¬categories=No%20publish%7CArchived%7cAutoArchived%7cdisputed&namespace=0&count=15&ordermethod=categoryadd&stablepages=only'
d=feedparser.parse(url)
for post in d['entries']:
label = Label(text=post.title)
root.add_widget(label)
return root
if __name__ == '__main__':
MyApp().run()