PyQt5 - приложение с графическим интерфейсом для получения IP-адреса

Опубликовано: 7 Апреля, 2022

В этой статье мы увидим, как сделать простое приложение PyQt5 для получения IP-адреса.

IP-адрес: адрес Интернет-протокола - это числовая метка, присваиваемая каждому устройству, подключенному к компьютерной сети, которое использует Интернет-протокол для связи. IP-адрес выполняет две основные функции: идентификацию хоста или сетевого интерфейса и адресацию местоположения.

Необходимые модули и установка:

PyQt5: PyQt - это привязка Python к кроссплатформенному набору инструментов графического интерфейса Qt, реализованная как подключаемый модуль Python. PyQt - бесплатное программное обеспечение, разработанное британской фирмой Riverbank Computing.
Запросы: Запросы позволяют очень легко отправлять запросы 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

Below is the implementation

# 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 DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.