Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แสดงชื่อโฮสต์ (Host Name) และที่อยู่ IP บนหน้าต่าง Tkinter

เพื่อหาที่อยู่ IP ของผู้ใช้ ใช้ไลบรารี socket ของ Python เริ่มจาก query ชื่อโฮสต์ของอุปกรณ์ แล้วหา IP address ที่เกี่ยวข้อง

ตัวอย่างนี้ใช้ socket หาชื่อโฮสต์และ IP address แสดงบน label สองตัว

ขั้นตอน

  • นำเข้า tkinter และสร้าง instance ของ tkinter frame

  • กำหนดขนาด frame ด้วย geometry

  • ใช้ gethostname() ของ socket หาชื่อโฮสต์ เก็บใน "hostname"

  • ใช้ gethostbyname() ส่ง hostname เพื่อได้ IP address

  • สร้าง label สองตัวแสดง hostname และ IP address

  • รัน mainloop

ตัวอย่าง

from tkinter import *
import socket

root = Tk()
root.geometry("700x300")

hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)

label1 = Label(root, text="The Host Name is: " + hostname, font="Calibri, 20")
label1.pack(pady=50)
label2 = Label(root, text="The IP Address is: " + ip_address, font="Calibri, 20")
label2.pack(pady=20)

root.mainloop()

ผลลัพธ์

แสดงชื่อโฮสต์ (Host Name) และที่อยู่ IP บนหน้าต่าง Tkinter