一个使用Tkinter和Newsapi的简单新闻应用

一个使用Tkinter和Newsapi的简单新闻应用

Tkinter是一个用于制作Windows和UNIX操作系统桌面应用程序的Python库。Tkinter提供了许多选择,可以用于应用程序的小部件。使用Tkinter可以以不同的方式创建相同的小部件。

如今互联网上有大量的信息源。新闻不断从全球各地的信息源传来。追踪最新新闻是一项艰巨的任务。在本文中,我们将使用Tkinter和Newsapi构建一个简单的新闻应用程序。

什么是Newsapi

News API是一个提供通过JSON Web API访问世界各地新闻文章和突发新闻的应用程序编程接口(API)。 News API仅提供一个REST API,开发人员可以使用该API以JSON格式简单地获取所有新闻文章、标题等。

如何创建API密钥

  • 要使用News API,您需要通过访问News API 网站 来创建自己的API密钥。

  • 点击右上角的GetApiKey按钮。

  • 在出现的表单中填写您的基本信息。

  • 提交基本详细信息后,您的注册将完成,并且您将获得API密钥。
    一个使用Tkinter和Newsapi的简单新闻应用

使用Tkinter和Newsapi创建Web应用程序的步骤

步骤1-安装Tkinter和News Api

在开始实施Web应用程序之前,您需要在Python中安装Tkinter库和news API。打开命令提示符或终端,键入pip install命令。

pip install tk
pip install newsapi-python

Pip 是一个 Python 的包管理器。上述命令在你的本地文件系统中安装了 tkinter 和 newsapi。

步骤2 – 导入所需模块

导入 tkinter 和 newsapi 模块以在制作一个简单的新闻应用程序中使用它们。

import tkinter as tk
from newsapi import NewsApiClient

步骤3 – 创建一个新闻API客户端对象

一旦所有的库安装完毕,创建一个NewsAPI客户端对象,并使用从News API网站创建的API密钥进行初始化。

newsapi = NewsApiClient(api_key='your_api_key_here')

用你在NEWS API网站上创建的API替换your_api_key_here。

步骤4 – 创建一个获取最新新闻文章的函数

我们将创建一个名为get_news()的函数,它将检索最新的新闻标题,并将它们显示为app中的文本小部件。此外,在检索新的新闻文章标题之前,我们需要清除屏幕。

def get_news():
   # Retrieve the top headlines
   top_headlines = newsapi.get_top_headlines(language='en')

   # Clear the text widget
   text.delete(1.0, tk.END)

   # Display the top headlines
   for article in top_headlines['articles']:
      text.insert(tk.END, article['title'] + '\n\n')

步骤5 – 创建一个简单的用户界面

现在我们将为我们的应用程序创建一个简单的用户界面,将新闻标题作为文本小部件显示在应用程序内部。应用程序底部的一个按钮显示“获取新闻”,点击按钮将从新闻API中检索新闻标题并在应用程序屏幕上显示它们。

# Create the main window
root = tk.Tk()
root.title('News App')

# Create the text widget
text = tk.Text(root, height=20, width=50)
text.pack()

# Create the button
button = tk.Button(root, text='Get News', command=get_news)
button.pack()

# Run the main loop
root.mainloop()

下面是简单 web 应用程序的完整代码:

示例

import tkinter as tk
from newsapi import NewsApiClient
newsapi = NewsApiClient(api_key='your_api_key_here')
def get_news():
   # Retrieve the top headlines
   top_headlines = newsapi.get_top_headlines(language='en')

   # Clear the text widget
   text.delete(1.0, tk.END)

   # Display the top headlines
   for article in top_headlines['articles']:
      text.insert(tk.END, article['title'] + '\n\n')
# Create the main window
root = tk.Tk()
root.title('News App')

# Create the text widget
text = tk.Text(root, height=20, width=50)
text.pack()

# Create the button
button = tk.Button(root, text='Get News', command=get_news)
button.pack()

# Run the main loop
root.mainloop()

输出

一个使用Tkinter和Newsapi的简单新闻应用

结论

在这篇文章中,我们了解了如何使用Tkinter和python的news API构建一个简单的网页应用程序。我们只是调用了news API提供的REST API,并在一个用户友好的界面中使用一个简单的文本小部件显示新闻标题。该应用程序可以扩展为包括更多功能,如按主题或来源筛选新闻,可以改进用户界面,还可以添加其他内容,以使应用程序对用户更具交互性。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程