Skip to content
Related Articles

Related Articles

GUI chat application using Tkinter in Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 11 Sep, 2022
View Discussion
Improve Article
Save Article

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



from tkinter import *
root = Tk()
BG_COLOR = "#17202A"
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"):
            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!")
        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(
txt = Text(root, bg=BG_COLOR, fg=TEXT_COLOR, font=FONT, width=60)
txt.grid(row=1, column=0, columnspan=2)
scrollbar = Scrollbar(txt), 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)




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 ‘'(say). Since only the clients will interact the server script does not have a GUI.



# 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
# 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,
# bind the address of the
# server to the socket
# function to start the connection
def startChat():
    print("server is working on " + SERVER)
    # listening for connections
    while True:
        # accept connections and returns
        # a new connection to the client
        #  and  the address bound to it
        conn, addr = server.accept()
        # 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
        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))
        # 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
    # close the connection
# method for broadcasting
# messages to the each clients
def broadcastMessage(message):
    for client in clients:
# call the method to
# begin the communication

Client-Side Script: 


# 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 file
from chat import *
PORT = 5050
FORMAT = "utf-8"
# Create a new client socket
# and connect to the server
client = socket.socket(socket.AF_INET,
# GUI class for the chat
class GUI:
    # constructor method
    def __init__(self):
        # chat window which is currently hidden
        self.Window = Tk()
        # login window
        self.login = Toplevel()
        # set the title
        # create a Label
        self.pls = Label(self.login,
                         text="Please login to continue",
                         font="Helvetica 14 bold")
        # create a Label
        self.labelName = Label(self.login,
                               text="Name: ",
                               font="Helvetica 12")
        # create a entry box for
        # tyoing the message
        self.entryName = Entry(self.login,
                               font="Helvetica 14")
        # set the focus of the cursor
        # create a Continue Button
        # along with action
        self.go = Button(self.login,
                         font="Helvetica 14 bold",
                         command=lambda: self.goAhead(self.entryName.get()))
    def goAhead(self, name):
        # the thread to receive messages
        rcv = threading.Thread(target=self.receive)
    # The main layout of the chat
    def layout(self, name):
 = name
        # to show chat window
        self.labelHead = Label(self.Window,
                               font="Helvetica 13 bold",

        self.line = Label(self.Window,
        self.textCons = Text(self.Window,
                             font="Helvetica 14",
        self.labelBottom = Label(self.Window,
        self.entryMsg = Entry(self.labelBottom,
                              font="Helvetica 13")
        # place the given widget
        # into the gui window,
        # create a Send Button
        self.buttonMsg = Button(self.labelBottom,
                                font="Helvetica 10 bold",
                                command=lambda: self.sendButton(self.entryMsg.get()))
        # create a scroll bar
        scrollbar = Scrollbar(self.textCons)
        # place the scroll bar
        # into the gui window,
    # function to basically start the thread for sending messages
    def sendButton(self, msg):
        self.msg = msg
        self.entryMsg.delete(0, END)
        snd = threading.Thread(target=self.sendMessage)
    # function to receive messages
    def receive(self):
        while True:
                message = client.recv(1024).decode(FORMAT)
                # if the messages from the server is NAME send the client's name
                if message == 'NAME':
                    # insert messages to text box
                # an error will be printed on the command line or console if there's an error
                print("An error occurred!")
    # function to send messages
    def sendMessage(self):
        while True:
            message = (f"{}: {self.msg}")
# create a GUI class object
g = GUI()


Login Window: 





My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!