Creating a Chatbot using Python Tkinter GUI toolkit
Tags: chatbot, python, softwaredevelopment, developer
Published: 2024-05-07 07:02:13

[Chatbot](https://www.googleadservices.com/pagead/aclk?sa=L&ai=DChcSEwiX2enVjeiFAxXVREECHcf0D9wYABABGgJ3cw&ase=2&gclid=Cj0KCQjwir2xBhC_ARIsAMTXk86lRABiiGgYB1p7eEeg3Y9J4aJR9M5pbLB-xB8Fz40mXBvb_AdRdqEaAuzpEALw_wcB&ohost=www.google.com&cid=CAESV-D2w6fWWsPHqRqqBaR3EuNKS9oQngLjc5hZ4JtCdxlnb7yBRdJjBXgvd1dKeB9EqkIKrbfuTdNUnYOZpetPo3edB0es6lQ59zNSIKuxku6JdHkFxpG73w&sig=AOD64_0SVpqtVL2w55qPFe5scjmJLTlZUA&q&nis=4&adurl&ved=2ahUKEwiw5-HVjeiFAxX2caQEHeYvDj4Q0Qx6BAgNEAE) is a software application that simulates human conversation through text or voice. They are created to answer FAQs (Frequently Asked Questions), provide full-time support to customers, handle inquiries, and reach out to agents for further support on issues that require human intervention.

In this project, I will show you how to create a Python chatbot powered by the Tkinter GUI (Graphical User Interface) toolkit. This chatbot will handle inquiries and answer questions on the DevOps Engineering Field.

##Setting up the Environment

- Install `Python` on your operating system by following these steps [here](https://www.python.org/downloads/)
- Install `Tkinter` by running this command on your bash/ VS Code terminal

```
pip install tk
```


- Create a folder and name it `Chatbot`
- Open the folder with `VS Code`
- Create a Python file and call it `Chatbot.py`

##Designing the User Interface

For convenient User interactions with the chatbot, consider designing a simple Graphical User Interface like this one.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7a37dktjfjr3ynacgfnm.png)

To achieve the above layout, you need to import the necessary libraries and put your code in order as follows:

####Importing the necessary libraries 

```
from tkinter import *
import tkinter as tk
from tkinter import PhotoImage
from tkinter import Label, Tk
from PIL import Image, ImageTk
import datetime
```


####Create a date and time function to greet the client as per visiting time. 

```
# greetings based on time opening chatbot
current_time = datetime.datetime.now()

if 6 <= current_time.hour <= 12:
    greeting = "Good Morning!"
elif 12 <= current_time.hour <= 16:
    greeting = "Good Afternoon!"
else:
    greeting = "Good Evening!"
```




####Create the main Tkinter GUI based on your size, color, and font.

```
# Tkinter UI/UX design
root=Tk()
root.title('DevOps Chatbot')
root.geometry('720x400+150+100')
root.configure(bg='light blue')
root.resizable(False, False)
```


####Create the heading of the chatbot

```
# Heading label to inform the user what to do
heading = Label(root, text=f"{greeting} 😄. I'm DevOps Chatbot. I have DevOps answers for you from the drop-down menu.", fg='#000', bg='white', font=('Microsoft YaHei UI Light', 10, 'bold'))
heading.place(x=10, y=5)
```


After the heading, there is the dropdown menu. Design appropriately adding necessary questions that the users are interested in or may ask. Write the questions as precisely as possible because they will fetch data from a JSON file.

```
# Dropdown Menu for the user to select
dropdown = tk.StringVar()
dropdown.set("Select a response")
dropdown_menu = tk.OptionMenu(root, dropdown, "What is DevOps", "DevOps Principles", "Benefits of adopting DevOps", "DevOps Career Paths", "DevOps Tools", "Learning Resources")
dropdown_menu.grid(row=1, column=0, padx=100, pady=100)
dropdown_menu.place(x=10, y=40)
dropdown_menu.config(width=70)
```


####Create an area where answers will be displayed

```
#This is where the user answers will be displayed
chat_history = Text(root, fg='black', border=2, bg='white', height=17, width=57, font=("cambria", 11))
chat_history.place(x=10, y=90)
```


###Create necessary buttons for navigation and interaction with the chatbot. 

This Chatbot will have three buttons;

The `Click for answers` button will display answers corresponding to the selection of the question.

The `Clear Screen` button will clear all the data in the chat area. 

The `Close Window` button will close the chatbot.

The following code shows how to design the buttons. 

```
# Button to ask the question
ask = Button(root, width=25, pady=7, text="Click for Answers", fg='black').place(x=500, y=90)

# Button to clear the screen
clear = Button(root, width=25, pady=7, text="Clear Screen", fg='black')
clear.place(x=500, y=150)

# Button to exit the chatbot
exit = Button(root, width=25, pady=7, text="Close Window", fg='black')
exit.place(x=500, y=210)
```


###Displaying DevOps image

Download the image and copy it to your current directory 

Resize the image to specific dimensions as you may need.

Set the place to display your image. 

```
# Open the image using Pillow
pil_img = Image.open('devops.png')

# Resize the image to specific dimensions (adjust width and height as needed)
width, height = 180, 110
pil_img = pil_img.resize((width, height), Image.BICUBIC)

# Convert Pillow image to Tkinter-compatible format
tk_img = ImageTk.PhotoImage(pil_img)

# Create a Label image to display the image
Label(root, image=tk_img, bg="white").place(x=500, y=270)

root.mainloop()
```


Run your code using the `VS Code` run command or by running the following command;

```
python Chatbot.py
```


##Building the Chatbot logic
###Create a Backend

This chatbot will load its data from a JSON file store the data in a dictionary and then create lists inside the dictionary. 

On your directory, create a new file and call it `answers.json`

After coming up with the desired FAQs from clients, create topics from the questions. 
The questions will be used on the dropdown menu. Further elaborations on the topics will be stored in `answers.json` file.

An example of a question like 
>`DevOps Career Paths`
will have an answer such as `DevOps Engineer` with a little explanation of the roles like `Plays a central role in implementing and managing DevOps Practices. They are responsible for automating build, deployment and release processes, configuring and managing infrastructure and ensuring smooth collaboration between development and operations teams`.

Choose a niche of your taste and work on it. 

###Handling user input and generating responses
Our chatbot has a dropdown menu, a chat area, a click for answers button, a clear screen, and a close window. 

When the user selects a quiz from the `dropdown menu` and `click for answers` button, an answer must be displayed in the `chat area`. 

The logic works as follows:

####Click for answers

```
# Create a dictionary to keep track of the last selected response index
last_selected_index = {}

# Response answer based on the selected question
def random_answers():
    selected_response = dropdown.get()
    if selected_response in answers:
        responses_list = answers[selected_response]
        if responses_list:

            # Display the questions in order
            last_index = last_selected_index.get(selected_response, -1)
            last_index = (last_index + 1) % len(responses_list)

            selected_response_text = responses_list[last_index]
            last_selected_index[selected_response] = last_index

            # View answers on the chatbot
            chat_history.config(state=tk.NORMAL)
            chat_history.insert(tk.END, f"{selected_response_text}\n\n")
            chat_history.config(state=tk.DISABLED)
        else:
            chat_history.config(state=tk.NORMAL)
            chat_history.insert(tk.END, "I don't have a response for that.\n\n")
            chat_history.config(state=tk.DISABLED)
```


Create a function to retrieve the data in the JSON file in order and view the answers on the chat area when the `Click for answers` button is clicked. 

Update the Tkinter user interface code to appear like this

```
# Button to ask the question
ask = Button(root, command=random_answers, width=25, pady=7, text="Click for Answers", fg='black').place(x=500, y=90)
```


####Clear Screen
When the user clicks this button, all the data in the chat area must be deleted. (The chat history will not be saved but it is possible to save the chat history).

Create a function for the `Clear Screen` button to delete chat history.

```
# Clear the chat history
def clear_screen():
    chat_history.config(state=tk.NORMAL)
    chat_history.delete('1.0', tk.END)
    chat_history.config(state=tk.DISABLED)
```


####Close Window
This button will exit the user interface and end all interactions with the user. 

The function behind this button is as hereunder;

```
# exit the chatbot
def exit_chat():
    root.quit()
```


After completing the above code, you should be able to select the `dropdown menu`, `clear screen`, and `close window`. `Click for answers` will not work since we have not integrated the frontend with the backend. 
Integrating the Frontend with the Backend.

##Integrating the Frontend with the Backend

After designing the user interface and JSON file, the final goal is to achieve a functional chatbot that will return responses when the user interacts with your interface. 

```
import json

# Load initial responses from a JSON file
answers = {}

try:
    with open('answers.json', 'r') as file:
        answers = json.load(file)
except FileNotFoundError:
    answers = {}
```


This Python code loads initial responses from a JSON file named `answers.json`. It first initializes an empty dictionary called `answers`. Then, it attempts to open the JSON file in read mode using a `with` statement. If the file is found, it loads the contents of the file into the `answers` dictionary using the `json.load()` function. If `FileNotFoundError` is not raised, it simply keeps the `answers` dictionary empty. 
###Testing the integration 
Run this command on your terminal to open the user interface and interact with the chatbot to verify that the chatbot is fully functional and ready for deployment and distribution. 

```
python chatbot.py
```


If the chatbot is running without errors, you can now decide to use it on your machine or create an executable file for deployment and distribution. 

##Conclusion 
Chatbots are ideal tools for communication in an organization since they can respond to Frequently Asked Questions (FAQs) with the user and the chatbot can be designed to redirect the user to seek further assistance elsewhere by providing links to websites and contacts to the organization’s customer care.

Chatbots can be easily modified and updated depending on the user's or organization’s demands. Nowadays, Artificial Intelligence is integrated with chatbots and the chatbots can learn as the user interacts with it and adjust the responses accordingly.