Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hiển thị Host Name và IP Address trên cửa sổ Tkinter

Dùng thư viện socket của Python: gethostname() lấy host name, gethostbyname() lấy IP.

Các bước

  • Nhập tkinter, socket.

  • Tạo cửa sổ, đặt kích thước.

  • Lấy hostname: socket.gethostname().

  • Lấy IP: socket.gethostbyname(hostname).

  • Tạo 2 Label hiển thị.

  • Chạy mainloop.

Ví dụ

from tkinter import *
import socket

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

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

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

root.mainloop()

Kết quả

Cửa sổ hiển thị Host Name và IP Address của máy.

Hiển thị Host Name và IP Address trên cửa sổ Tkinter