PyQt5 – 获取IP地址的GUI应用程序

PyQt5 – 获取IP地址的GUI应用程序

在这篇文章中,我们将看到如何制作一个简单的PyQt5应用程序来获取IP地址

IP地址: 互联网协议地址是分配给每个连接到使用互联网协议的计算机网络的设备的数字标签。IP地址有两个主要功能:主机或网络接口识别和位置寻址。

需要的模块和安装:

PyQt5 : PyQt5是跨平台GUI工具包Qt的Python绑定,作为Python插件实现。PyQt5是由英国公司Riverbank Computing开发的免费软件。

Requests : Requests允许你非常容易地发送HTTP/1.1请求。不需要手动添加查询字符串到你的URLs。

实施步骤:

1.创建一个窗口

2.创建按钮并设置其几何形状

3.创建标签并设置其几何形状、边界和对齐方式

4.为按钮添加动作,即当按钮被按下时,动作方法应被调用。

5.在动作方法的帮助下,获取数据。过滤数据以获得IP地址

6.借助标签在屏幕上显示IP地址。

下面是实现方法

# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import requests
import sys
 
 
class Window(QMainWindow):
 
    def __init__(self):
        super().__init__()
 
        # setting title
        self.setWindowTitle("Python ")
 
        # setting geometry
        self.setGeometry(100, 100, 400, 500)
 
        # calling method
        self.UiComponents()
 
        # showing all the widgets
        self.show()
 
    # method for widgets
    def UiComponents(self):
 
        # create push button to perform function
        push = QPushButton("Press", self)
 
        # setting geometry to the push button
        push.setGeometry(125, 100, 150, 40)
 
        # creating label to show the ip
        self.label = QLabel("Press button to see your IP", self)
 
        # setting geometry to the push button
        self.label.setGeometry(100, 200, 200, 40)
 
        # setting alignment to the text
        self.label.setAlignment(Qt.AlignCenter)
 
        # adding border to the label
        self.label.setStyleSheet("border : 3px solid black;")
 
        # adding action to the push button
        push.clicked.connect(self.get_ip)
 
    # method called by push
    def get_ip(self):
 
        # getting data
        r = requests.get("http://httpbin.org / ip")
         
        # json data with key as origin
        ip = r.json()['origin']
 
        # parsing the data
        parsed = ip.split(", ")[0]
 
        # showing the ip in label
        self.label.setText(parsed)
 
        # setting font
        self.label.setFont(QFont('Times', 12))
 
 
 
# create pyqt5 app
App = QApplication(sys.argv)
 
# create the instance of our Window
window = Window()
 
window.show()
 
# start the app
sys.exit(App.exec())
Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册