Display the Host Name and IP Address on a Tkinter Window
Tkinter is a popular GUI toolkit that allows developers to create user-friendly desktop applications using the Python programming language. In this tutorial, we’ll show you how to display the host name and IP address on a Tkinter window.
Prerequisites
Before we start, make sure you have Python installed on your system. You can download and install Python from the official website (https://www.python.org/downloads/).
Displaying Host Name and IP Address
To display the host name and IP address on a Tkinter window, we’ll need to use the socket
module, which provides us with network communication services. Here’s the code that we’ll use for this tutorial:
import socket
import tkinter as tk
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
except:
ip = "127.0.0.1"
finally:
s.close()
return ip
def get_host_name():
return socket.gethostname()
root = tk.Tk()
root.title("Host Info")
host_name = get_host_name()
ip_address = get_host_ip()
tk.Label(root, text="Host Name:").grid(row=0, sticky=tk.W)
tk.Label(root, text=host_name).grid(row=0, column=1, sticky=tk.W)
tk.Label(root, text="IP Address:").grid(row=1, sticky=tk.W)
tk.Label(root, text=ip_address).grid(row=1, column=1, sticky=tk.W)
root.mainloop()
Let’s go through this code step-by-step.
First, we import the required modules – socket
and tkinter
. We then define two functions get_host_ip()
and get_host_name()
that will retrieve the IP address and host name respectively.
get_host_ip()
creates a new UDP socket and connects it to a well-known IP address (8.8.8.8
) and port number (80
). This UDP connection is then used to determine the IP address of the local host. If there’s an exception while creating the socket, which is usually due to network issues, the function returns the IP address as 127.0.0.1
.
get_host_name()
uses a built-in method of the socket
module to retrieve the host name of the current system.
We then create a new Tk
instance, set the title of the window to “Host Info”, and use get_host_ip()
and get_host_name()
to retrieve the IP address and host name respectively.
We then create two Label
components to display the host name and IP address on the window. The grid()
method is used to position the labels on the window.
Finally, we initiate the main loop of the GUI using mainloop()
method.
Conclusion
In this tutorial, we demonstrated how to display the host name and IP address on a Tkinter window. We used the socket
module to retrieve the IP address and host name of the current system and used the Label
component of Tkinter to display the information on the window. We hope this tutorial has been useful to you in understanding how Tkinter can be used to create simple GUI applications.