在 Tkinter 視窗上顯示主機名稱和 IP 地址


要獲取使用者的 IP 地址,我們可以使用 Python 本機的網路介面 socket。首先,我們需要查詢裝置的主機名,然後獲取其關聯的 IP 地址。

在此示例中,我們將使用 socket 庫來獲取主機名和 IP 地址,並在兩個標籤上列印詳細資訊。

步驟 −

  • 匯入 tkinter 庫並建立 tkinter 框架的例項。

  • 使用 geometry 方法設定框架的大小。

  • 接下來,使用 socket 庫的 gethostname() 方法獲取主機名,並將其儲存在變數 “hostname” 中。

  • 然後使用 gethostbyname() 方法並傳入主機名來獲取 IP 地址。

  • 建立兩個標籤以在視窗上顯示主機名和 IP 地址。

  • 最後,執行應用程式視窗的 mainloop

示例

# Import the tkinter library
from tkinter import *
import socket

# Create an instance of tkinter frame
root = Tk()

# Size of the window
root.geometry("700x300")

# hostname of the socket
hostname = socket.gethostname()

# IP address of the hostname
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()

輸出

將產生以下輸出 −

更新於: 26-Oct-2021

781 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告