Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Display the Host Name and IP Address on a Tkinter Window
To obtain a user's IP address, we can use Python's native networking interface, socket. First of all, we need to query the device's host name and then get its associated IP address.
In this example, we will use the socket library to get the host name and IP address and display the details on two labels in a Tkinter window.
Steps
Import the tkinter library and create an instance of tkinter frame.
Set the size of the frame using geometry method.
Next, use the gethostname() method of socket library to get the host name and store it in a variable "hostname".
Then use the gethostbyname() method and pass the hostname in it to get the IP address.
Create two labels to display the hostname and IP address on the window.
Finally, run the mainloop of the application window.
Example
Here's how to create a Tkinter window that displays the host name and IP address −
# Import the tkinter library
from tkinter import *
import socket
# Create an instance of tkinter frame
root = Tk()
# Size of the window
root.geometry("700x300")
root.title("Host Information")
# 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()
Output
It will produce the following output −
Key Methods Explained
socket.gethostname()
Returns the hostname of the machine where the Python interpreter is currently executing.
socket.gethostbyname()
Takes a hostname as an argument and returns the corresponding IP address.
Alternative Implementation with Error Handling
For more robust code, you can add error handling −
from tkinter import *
import socket
root = Tk()
root.geometry("700x300")
root.title("Host Information")
try:
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
Label(root, text=f"Host Name: {hostname}", font="Calibri, 20").pack(pady=50)
Label(root, text=f"IP Address: {ip_address}", font="Calibri, 20").pack(pady=20)
except socket.error as e:
Label(root, text=f"Error: {e}", font="Calibri, 16", fg="red").pack(pady=100)
root.mainloop()
Conclusion
Using the socket module with Tkinter allows you to easily display network information in a GUI. The gethostname() and gethostbyname() methods provide a simple way to retrieve the host name and IP address of the current machine.
