The Wayback Machine - https://web.archive.org/web/20240906205022/https://www.geeksforgeeks.org/gui-chat-application-using-tkinter-in-python/
Open In App

GUI chat application using Tkinter in Python

Last Updated : 11 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Chatbots are computer program that allows user to interact using input methods. The Application of chatbots is to interact with customers in big enterprises or companies and resolve their queries.  Chatbots are mainly built for answering standard FAQs.

The benefit of this type of system is that customer is no longer required to follow the same traditional mean of communication Instead they can just chat with the bot and can resolve their query.

Example 1) This is a simple GUI (Graphical User Interface) chat application where users can interact with the bot.

Prerequisites: Tkinter

pip install tkinter

Example

Python




from tkinter import *
 
# GUI
root = Tk()
root.title("Chatbot")
 
BG_GRAY = "#ABB2B9"
BG_COLOR = "#17202A"
TEXT_COLOR = "#EAECEE"
 
FONT = "Helvetica 14"
FONT_BOLD = "Helvetica 13 bold"
 
# Send function
def send():
    send = "You -> " + e.get()
    txt.insert(END, "\n" + send)
 
    user = e.get().lower()
 
    if (user == "hello"):
        txt.insert(END, "\n" + "Bot -> Hi there, how can I help?")
 
    elif (user == "hi" or user == "hii" or user == "hiiii"):
        txt.insert(END, "\n" + "Bot -> Hi there, what can I do for you?")
 
    elif (user == "how are you"):
        txt.insert(END, "\n" + "Bot -> fine! and you")
 
    elif (user == "fine" or user == "i am good" or user == "i am doing good"):
        txt.insert(END, "\n" + "Bot -> Great! how can I help you.")
 
    elif (user == "thanks" or user == "thank you" or user == "now its my time"):
        txt.insert(END, "\n" + "Bot -> My pleasure !")
 
    elif (user == "what do you sell" or user == "what kinds of items are there" or user == "have you something"):
        txt.insert(END, "\n" + "Bot -> We have coffee and tea")
 
    elif (user == "tell me a joke" or user == "tell me something funny" or user == "crack a funny line"):
        txt.insert(
            END, "\n" + "Bot -> What did the buffalo say when his son left for college? Bison.! ")
 
    elif (user == "goodbye" or user == "see you later" or user == "see yaa"):
        txt.insert(END, "\n" + "Bot -> Have a nice day!")
 
    else:
        txt.insert(END, "\n" + "Bot -> Sorry! I didn't understand that")
 
    e.delete(0, END)
 
 
lable1 = Label(root, bg=BG_COLOR, fg=TEXT_COLOR, text="Welcome", font=FONT_BOLD, pady=10, width=20, height=1).grid(
    row=0)
 
txt = Text(root, bg=BG_COLOR, fg=TEXT_COLOR, font=FONT, width=60)
txt.grid(row=1, column=0, columnspan=2)
 
scrollbar = Scrollbar(txt)
scrollbar.place(relheight=1, relx=0.974)
 
e = Entry(root, bg="#2C3E50", fg=TEXT_COLOR, font=FONT, width=55)
e.grid(row=2, column=0)
 
send = Button(root, text="Send", font=FONT_BOLD, bg=BG_GRAY,
              command=send).grid(row=2, column=1)
 
root.mainloop()


Output:

 

 

Example 2: This is a simple GUI (Graphical User Interface) chat application where multiple users can connect with each other in a client-server architecture i.e the clients will interact with the help of the server.

Prerequisites: Tkinter, Socket Programming, and Multithreading

Server Side Script:  This script file name is ‘client.py'(say). Since only the clients will interact the server script does not have a GUI.

Example

Python3




# import socket library
import socket
 
# import threading library
import threading
 
# Choose a port that is free
PORT = 5000
 
# An IPv4 address is obtained
# for the server.
SERVER = socket.gethostbyname(socket.gethostname())
 
# Address is stored as a tuple
ADDRESS = (SERVER, PORT)
 
# the format in which encoding
# and decoding will occur
FORMAT = "utf-8"
 
# Lists that will contains
# all the clients connected to
# the server and their names.
clients, names = [], []
 
# Create a new socket for
# the server
server = socket.socket(socket.AF_INET,
                       socket.SOCK_STREAM)
 
# bind the address of the
# server to the socket
server.bind(ADDRESS)
 
# function to start the connection
 
 
def startChat():
 
    print("server is working on " + SERVER)
 
    # listening for connections
    server.listen()
 
    while True:
 
        # accept connections and returns
        # a new connection to the client
        #  and  the address bound to it
        conn, addr = server.accept()
        conn.send("NAME".encode(FORMAT))
 
        # 1024 represents the max amount
        # of data that can be received (bytes)
        name = conn.recv(1024).decode(FORMAT)
 
        # append the name and client
        # to the respective list
        names.append(name)
        clients.append(conn)
 
        print(f"Name is :{name}")
 
        # broadcast message
        broadcastMessage(f"{name} has joined the chat!".encode(FORMAT))
 
        conn.send('Connection successful!'.encode(FORMAT))
 
        # Start the handling thread
        thread = threading.Thread(target=handle,
                                  args=(conn, addr))
        thread.start()
 
        # no. of clients connected
        # to the server
        print(f"active connections {threading.activeCount()-1}")
 
# method to handle the
# incoming messages
 
 
def handle(conn, addr):
 
    print(f"new connection {addr}")
    connected = True
 
    while connected:
          # receive message
        message = conn.recv(1024)
 
        # broadcast message
        broadcastMessage(message)
 
    # close the connection
    conn.close()
 
# method for broadcasting
# messages to the each clients
 
 
def broadcastMessage(message):
    for client in clients:
        client.send(message)
 
 
# call the method to
# begin the communication
startChat()


Client-Side Script: 

Python3




# import all the required  modules
import socket
import threading
from tkinter import *
from tkinter import font
from tkinter import ttk
 
# import all functions /
#  everything from chat.py file
from chat import *
 
PORT = 5050
SERVER = "192.168.0.103"
ADDRESS = (SERVER, PORT)
FORMAT = "utf-8"
 
# Create a new client socket
# and connect to the server
client = socket.socket(socket.AF_INET,
                       socket.SOCK_STREAM)
client.connect(ADDRESS)
 
 
# GUI class for the chat
class GUI:
    # constructor method
    def __init__(self):
 
        # chat window which is currently hidden
        self.Window = Tk()
        self.Window.withdraw()
 
        # login window
        self.login = Toplevel()
        # set the title
        self.login.title("Login")
        self.login.resizable(width=False,
                             height=False)
        self.login.configure(width=400,
                             height=300)
        # create a Label
        self.pls = Label(self.login,
                         text="Please login to continue",
                         justify=CENTER,
                         font="Helvetica 14 bold")
 
        self.pls.place(relheight=0.15,
                       relx=0.2,
                       rely=0.07)
        # create a Label
        self.labelName = Label(self.login,
                               text="Name: ",
                               font="Helvetica 12")
 
        self.labelName.place(relheight=0.2,
                             relx=0.1,
                             rely=0.2)
 
        # create a entry box for
        # tyoing the message
        self.entryName = Entry(self.login,
                               font="Helvetica 14")
 
        self.entryName.place(relwidth=0.4,
                             relheight=0.12,
                             relx=0.35,
                             rely=0.2)
 
        # set the focus of the cursor
        self.entryName.focus()
 
        # create a Continue Button
        # along with action
        self.go = Button(self.login,
                         text="CONTINUE",
                         font="Helvetica 14 bold",
                         command=lambda: self.goAhead(self.entryName.get()))
 
        self.go.place(relx=0.4,
                      rely=0.55)
        self.Window.mainloop()
 
    def goAhead(self, name):
        self.login.destroy()
        self.layout(name)
 
        # the thread to receive messages
        rcv = threading.Thread(target=self.receive)
        rcv.start()
 
    # The main layout of the chat
    def layout(self, name):
 
        self.name = name
        # to show chat window
        self.Window.deiconify()
        self.Window.title("CHATROOM")
        self.Window.resizable(width=False,
                              height=False)
        self.Window.configure(width=470,
                              height=550,
                              bg="#17202A")
        self.labelHead = Label(self.Window,
                               bg="#17202A",
                               fg="#EAECEE",
                               text=self.name,
                               font="Helvetica 13 bold",
                               pady=5)
 
        self.labelHead.place(relwidth=1)
        self.line = Label(self.Window,
                          width=450,
                          bg="#ABB2B9")
 
        self.line.place(relwidth=1,
                        rely=0.07,
                        relheight=0.012)
 
        self.textCons = Text(self.Window,
                             width=20,
                             height=2,
                             bg="#17202A",
                             fg="#EAECEE",
                             font="Helvetica 14",
                             padx=5,
                             pady=5)
 
        self.textCons.place(relheight=0.745,
                            relwidth=1,
                            rely=0.08)
 
        self.labelBottom = Label(self.Window,
                                 bg="#ABB2B9",
                                 height=80)
 
        self.labelBottom.place(relwidth=1,
                               rely=0.825)
 
        self.entryMsg = Entry(self.labelBottom,
                              bg="#2C3E50",
                              fg="#EAECEE",
                              font="Helvetica 13")
 
        # place the given widget
        # into the gui window
        self.entryMsg.place(relwidth=0.74,
                            relheight=0.06,
                            rely=0.008,
                            relx=0.011)
 
        self.entryMsg.focus()
 
        # create a Send Button
        self.buttonMsg = Button(self.labelBottom,
                                text="Send",
                                font="Helvetica 10 bold",
                                width=20,
                                bg="#ABB2B9",
                                command=lambda: self.sendButton(self.entryMsg.get()))
 
        self.buttonMsg.place(relx=0.77,
                             rely=0.008,
                             relheight=0.06,
                             relwidth=0.22)
 
        self.textCons.config(cursor="arrow")
 
        # create a scroll bar
        scrollbar = Scrollbar(self.textCons)
 
        # place the scroll bar
        # into the gui window
        scrollbar.place(relheight=1,
                        relx=0.974)
 
        scrollbar.config(command=self.textCons.yview)
 
        self.textCons.config(state=DISABLED)
 
    # function to basically start the thread for sending messages
    def sendButton(self, msg):
        self.textCons.config(state=DISABLED)
        self.msg = msg
        self.entryMsg.delete(0, END)
        snd = threading.Thread(target=self.sendMessage)
        snd.start()
 
    # function to receive messages
    def receive(self):
        while True:
            try:
                message = client.recv(1024).decode(FORMAT)
 
                # if the messages from the server is NAME send the client's name
                if message == 'NAME':
                    client.send(self.name.encode(FORMAT))
                else:
                    # insert messages to text box
                    self.textCons.config(state=NORMAL)
                    self.textCons.insert(END,
                                         message+"\n\n")
 
                    self.textCons.config(state=DISABLED)
                    self.textCons.see(END)
            except:
                # an error will be printed on the command line or console if there's an error
                print("An error occurred!")
                client.close()
                break
 
    # function to send messages
    def sendMessage(self):
        self.textCons.config(state=DISABLED)
        while True:
            message = (f"{self.name}: {self.msg}")
            client.send(message.encode(FORMAT))
            break
 
 
# create a GUI class object
g = GUI()


OUTPUT : 

Login Window: 

CLIENT 1: 

CLIENT 2:

 CLIENT 3:

 SERVER:



Similar Reads

Python | ToDo GUI Application using Tkinter
Prerequisites : Introduction to tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create a ToDo GUI application using Tkinter, with a step-by-step guide. To create a tkinter : Importing the module – tkinter
5 min read
Build GUI Application for Guess Indian State using Tkinter Python
In this article, you will learn to make a GUI game in Python, in which we will be shown a map of Indian states and an input prompt were in the prompt, the user has to enter a state name of India. If the user guessed it correctly, the name would hover over its location on the map. You can also see the score as the title of the input prompt window. M
8 min read
Create First GUI Application using Python-Tkinter
We are now stepping into making applications with graphical elements, we will learn how to make cool apps and focus more on its GUI(Graphical User Interface) using Tkinter. What is Tkinter?Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python sta
12 min read
Python | Simple GUI calculator using Tkinter
Prerequisite: Tkinter Introduction, lambda function Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI a
6 min read
Python | Distance-time GUI calculator using Tkinter
Prerequisites : Introduction to Tkinter | Using google distance matrix API Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest wa
7 min read
Python | Create a GUI Marksheet using Tkinter
Create a python GUI mark sheet. Where credits of each subject are given, enter the grades obtained in each subject and click on Submit. The credits per subject, the total credits as well as the SGPA are displayed after being calculated automatically. Use Tkinter to create the GUI interface. Refer the below articles to get the idea about basics of t
8 min read
Python: Weight Conversion GUI using Tkinter
Prerequisites: Python GUI – tkinterPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Crea
2 min read
Python | GUI Calendar using Tkinter
Prerequisites: Introduction to Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a GUI Calendar application using
4 min read
Sentiment Detector GUI using Tkinter - Python
Prerequisites : Introduction to tkinter | Sentiment Analysis using Vader Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to creat
4 min read
Python - Morse Code Translator GUI using Tkinter
Prerequisites : Introduction to tkinter | Morse Code Translator Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a Morse
6 min read
Python - SpongeBob Mocking Text Generator GUI using Tkinter
Prerequisites : Introduction to tkinter | SpongeBob Mocking Text Generator Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to cre
4 min read
Python - Spell Corrector GUI using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a GUI Spell Corrector application using Tkinter, with a step-by-step gu
5 min read
Python - UwU text convertor GUI using Tkinter
Prerequisites :Introduction to tkinter | UwU text convertor Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to crea
4 min read
GST Rate Finder GUI using Python-Tkinter
Prerequisites : Introduction to tkinter | Program to calculate GSTPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create GST Rate Finder GUI application using Tkinter, with a step-by-step guide. To create a Tki
3 min read
Create Copy-Move GUI using Tkinter in Python
Everyone reading this post is well aware of the importance of Copying the file or moving the file from one specific location to another. In this post, we have tried to explain not only the program but added some exciting pieces of Interface. Up to now, many of you may get about what we are talking about. Yes, you are right, We are going to use "Tki
4 min read
Python - English (Latin) to Hindi (Devanagiri) text convertor GUI using Tkinter
Prerequisites : Introduction to tkinter | Text transliteration from English to Indian languages – Using indic-transliterationPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python
4 min read
Standard GUI Unit Converter using Tkinter in Python
Prerequisites: Introduction to tkinter, Introduction to webbrowser In this article, we will learn how to create a standard converter using tkinter. Now we are going to create an introduction window that displays loading bar, welcome text, and user's social media profile links so that when he/she shares his code with some others, they can contact th
12 min read
Text to speech GUI convertor using Tkinter in Python
Prerequisite: Introduction to Tkinter Tkinter is the standard GUI library for Python. Python when combined with tkinter provides a fast and easy way to create GUI applications.By this library we can make a compelling choice for building GUI applications in Python, especially for applications where a modern sheen is unnecessary, and the top priority
3 min read
Python - Dynamic GUI Calculator using Tkinter module
Python provides many options for developing GUI like Kivy, PyQT, WxPython, and several others. Tkinter is the one that is shipped inbuilt with python which makes it the most commonly used out of all. Tkinter is easy, fast, and powerful. Beginners can easily learn to create a simple calculator using this article: Python | Simple GUI calculator using
3 min read
Tic Tac Toe game with GUI using tkinter in Python
Tic-tac-toe (American English), noughts and crosses (British English), or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. tkinter Python library is used to create the GUI.
15+ min read
Scientific GUI Calculator using Tkinter in Python
Prerequisite: Python GUI – tkinter In this article, we are going to create GUI Scientific Calculator using Python. As you can see, calculating large numbers nowadays is difficult or time-consuming. We've created a simple Scientific Calculator GUI using Python that allows you to perform simple and complex calculations. To implement GUI we will use t
13 min read
Python - Compound Interest GUI Calculator using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the Python GUI Libraries, Tkinter is the most commonly used method. In this article, we will learn how to create a Compound Interest GUI Calculator application using Tkinter. Let’s create a GUI-based Compound Interest Calculator application. Importing the mod
6 min read
Rank Based Percentile Gui Calculator using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create a Rank Based - Percentile Gui Calculator application using Tkinter, with a step-by-step guide. Prerequisites: Introduction to TkinterProgram to calculate t
7 min read
Create a GUI to check Domain Availability using Tkinter
There might be a case where a user wants to create a website and having certain ideas for the website's name but is struck on their availability. So let's develop a GUI that will check for domain availability. We will use the Python-whois module to get information about the website. It's able to extract data for all the popular TLDs (com, org, net,
2 min read
Create a GUI to Get Domain Information Using Tkinter
Prerequisites: Python GUI – tkinter Domain information is very important for every user. It contains information like Name, organization, State, city, Ip address, emails, server name, etc. In this article, we will write code for getting domain information and bind it with GUI Application. We will use the Python-whois module to get information about
2 min read
Ratio Calculator GUI using Tkinter
Prerequisite: Python GUI – tkinter Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. It is a standard Python interface to the Tk GUI toolkit shipped with Python. As Tk and Tkinter are available on most of the Unix platforms as well as on the Windows system, developing GUI applications with Tkinter be
3 min read
Python GUI - PyQt VS TKinter
A GUI toolkit contains widgets that are used to create a graphical interface. Python includes a wide range of Interface implementations available, from TkInter (it comes with Python, ) to a variety of various cross-platform solutions, such as PyQt5, which is known for its more sophisticated widgets and sleek look. PyQt PyQt is a toolkit for graphic
4 min read
How to add PDF in Tkinter GUI Python ?
In this article, We are going to see how to add a PDF file Tkinter GUI, For that, we don't have a direct widget to do this. For that, We need to have python version 2.7 or more. And you need to install the 'tkPDFViewer' library. This library allows you to embed the PDF file in your Tkinter GUI. Installation: To install this library you just have to
2 min read
How to embed Matplotlib charts in Tkinter GUI?
Prerequisite: Introduction to Tkinter | Introduction to Matplotlib When Matplotlib is used from Python shell, the plots are displayed in a default window. The plots can be embedded in many graphical user interfaces like wxpython, pygtk, or Tkinter. These various options available as a target for the output plot are referred to as 'backends'. There
3 min read
Simple chat Application using Websockets with FastAPI
In this article, we'll delve into the concept of WebSockets and their role in facilitating bidirectional communication between clients and servers. Subsequently, we'll embark on the journey of building a real-time multi-client chat application. This application will empower numerous users to connect to the server via the WebSocket protocol, fosteri
6 min read