PyQt5 – 获取 IP 地址的 GUI 应用程序
在本文中,我们将看到如何制作一个简单的 PyQt5 应用程序来获取 IP 地址
IP 地址: Internet 协议地址是分配给连接到使用 Internet 协议进行通信的计算机网络的每个设备的数字标签。 IP 地址有两个主要功能:主机或网络接口识别和位置寻址。
所需模块和安装:
PyQt5: PyQt 是跨平台 GUI 工具包 Qt 的Python绑定,实现为Python插件。 PyQt 是由英国公司 Riverbank Computing 开发的免费软件。
Requests : Requests 允许您非常轻松地发送 HTTP/1.1 请求。无需手动将查询字符串添加到您的 URL。
Steps for implementation :
1. Create a window
2. Create push button and set its geometry
3. Create label and set its geometry, border and alignment
4. Add action to the push button i.e when button get pressed action method should get called
5. Inside the action method with the help of requests to fetch the data
6. Filter the data to the get the IP address
7. Show IP address on the screen with the help of label
下面是实现
# 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())
输出 :