代码:
import requests
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton
from PyQt5.QtGui import QFont
def
get_public_ip
()
:
try:
response = requests.get(
'https://api.ipify.org?format=json'
)
data = response.json()
public_ip = data[
'ip'
]
return
public_ip
except Exception as
e:
return
None
class
MainWindow
(
QMainWindow
):
def
__init__
(
self
)
:
super
().__init_
_
()
self
.setWindowTitle(
"公网IP地址查询工具---微信公众号:蓝胖子之家"
)
self
.setFixedSize(
576
,
283
)
self
.label = QLabel(
"获取本机公网IP地址"
,
self
)
self
.label.setGeometry(
50
,
50
,
476
,
30
)
self
.label.setFont(QFont(
"Arial"
,
16
))
self
.ip_textbox = QLineEdit(
self
)
self
.ip_textbox.setGeometry(
50
,
90
,
476
,
30
)
self
.ip_textbox.setReadOnly(True)
self
.ip_textbox.setStyleSheet(
"QLineEdit { background-color: #f2f2f2; border: 1px solid #ccc; font-size: 14px; }"
)
self
.ip_textbox.setFont(QFont(
"Arial"
,
14
))
self
.button = QPushButton(
"一键获取IP"
,
self
)
self
.button.setGeometry(
200
,
140
,
176
,
40
)
self
.button.setStyleSheet(
"QPushButton { background-color: #4CAF50; color: white; border: none; font-size: 16px; }"
"QPushButton:hover { background-color: #45a049; }"
)
self
.button.setFont(QFont(
"Arial"
,
16
))
self
.button.clicked.connect(
self
.show_public_ip)
def
show_public_ip
(
self
)
:
public_ip = get_public_ip()
if
public_ip:
self
.ip_textbox.setText(public_ip)
else:
self
.ip_textbox.setText(
"获取公网IP地址时发生错误"
)
# 创建应用程序
app = QApplication([])
# 创建主窗口
window = MainWindow()
# 显示窗口
window.show()
# 运行应用程序
app.exec
_
()
在代码里首先导入了所需的库:requests
用于发送HTTP请求,PyQt5.QtWidgets
和PyQt5.QtGui
用于创建GUI窗口。
get_public_ip()
函数使用requests.get()
方法发送GET请求到https://api.ipify.org?format=json
,并从返回的JSON数据中提取出公网IP地址。如果请求成功,就返回公网IP地址;否则返回None。
接下来定义了一个MainWindow
类,继承自QMainWindow
。在构造函数中,设置了窗口的标题、固定大小,并创建了标签、文本框和按钮。
标签label
用于显示"获取本机公网IP地址",设置了字体和位置。
文本框ip_textbox
用于显示公网IP地址,设置了只读属性、样式和字体。
按钮button
用于触发获取公网IP地址的操作,设置了样式和字体,并连接了clicked
信号和show_public_ip()
槽函数。
show_public_ip()
方法调用get_public_ip()
函数获取公网IP地址,并将其显示在文本框中。如果获取成功,文本框显示公网IP地址;否则显示"获取公网IP地址时发生错误"。
最后,创建了一个应用程序对象app
,并创建了一个MainWindow
对象window
作为主窗口。调用window.show()
显示窗口,并通过app.exec_()
运行应用程序。
运行效果:
原文始发于微信公众号(蓝胖子之家):Python写获取本机公网ip地址工具
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论