FukatSoft

Loading

Wednesday, June 4, 2025
Latest Blogs
Create Your Own Smart Chatbot: A Step-by-Step Guide to Building a GUI Using DialoGPT and Tkinter"
Fizza Arif
May 13 2025 06:43 PM
101
0

Introduction


In today's world, chatbots are integral to online customer service and to improving self-productivity in an AI-powered world. This article will guide you through the steps of building a desktop chatbot using DialoGPT from Microsoft and the Tkinter library in Python. Our focus is on creating a visually dynamic window that responds to user input with an AI-generated speech that mimics natural conversation. We developed a custom graphical user interface (GUI) for DialoGPT and configured it to operate locally on your device. This project is for everyone excited about artificial intelligence; as a preliminary endeavor, it can help people understand the basics of chatbot architecture, chatbot construction, digital assistants, or contribute to AI more enjoyably.


Key Features & Technique


This chatbot uses Microsoft’s DialoGPT-medium language model, which is a transformer-based language model which is designed to have realistic dialogue. When you type into it it first breaks down the entire message into small fragments (tokenization) so that the language model can process the language more easily. To make the response sound as natural as possible, it also utilizes smart sampling techniques like top-p and temperature to keep the conversation going. It also stores all of your previous messages in a variable named chat_history_ids, so that the computer doesn't forget what you just typed. The interaction itself is built using Tkinter and its blend of the pack() and grid() layout methods to give the user a quiet and dynamic user interface.

Pros and Cons


Pros

Cons

Easy to use and extend

Chat history is lost on app close (no persistent storage) 

Uses a powerful pretrained language model.

DialoGPT is not always accurate or factual

Cross-platform support.

Can become repetitive in long sessions

GUI looks polished and modern.

Not suitable for sensitive or mission-critical applications without fine-tuning and moderation.

 

Advantages

  • Interactive GUI:  Provides a modern, responsive interface instead of relying on command-line input.
  • Natural Conversation Flow: Powered by DialoGPT, responses feel human-like and coherent.
  • Hugging Face Integration: Seamlessly fetches pretrained models via transformers and huggingface_hub.
  • Session Memory: Maintains conversation context to improve relevance across turns.
  • Custom Controls: Offers message history viewing, chat clearing, and multiple user commands.
  • Cross-platform: Tkinter is supported on Windows, macOS, and Linux.

 

Step-by-Step Process


   1. Setup & Requirements


On how to run the chatbot application, we need to install a few libraries. Transformers library (Hugging Face) to load and interact with the DialoGPT model, torch (PyTorch) to run the underlying machine learning computations. We also need huggingface_hub to authenticate and download the model from Hugging Face. The last library is tkinter for building the graphical user interface (packages are pre-installed with Python, so we don’t normally need to install anything separately). Run the following command to install all of the packages

pip install transformers huggingface_hub torch\


    2. Initialization


login(token="token_id") 

model_name = "microsoft/DialoGPT-medium" 

tokenizer = AutoTokenizer.from_pretrained(model_name)

model = AutoModelForCausalLM.from_pretrained(model_name) 

chat_history_ids = None 

step = 0 

chat_log = []

This code section describes how the chatbot is going to work and above all logins into Hugging Face using a personal access token (since it encrypts the password that will be used to download the models) loads the model pre trained by DialoGPT-medium and also tokenizer (which is used to understand texts) and finally initializes the variables chat_history_ids, step and chat_log: in case of interest chat_log will be updated periodically as well as the history of the messages that have been sent so this does not change.

 

After that, a class named app is made in which the following functions have been added.


    3. Setting Up the Interface


It essentially starts with the __init__ method. It creates the main window and gives it a custom title and theme. It will set the background color, minimum size, and enable resizing. It uses a combo of grid and pack geometry managers to keep it clean and responsive. This main frame has the chat area (where the message will appear) and a scrollbar so you can browse through a long conversation. The chat is styled to look modern and readable, and is initially set to read-only so nobody changes what you sent

def __init__(self, root): 

self.root = root 

self.root.title("💬 DialoGPT Chatbot") 

self.root.configure(bg="#1e1e2f") 

self.root.minsize(600, 500) 

self.root.geometry("700x600") 

self.root.resizable(True, True) 

self.root.rowconfigure(0, weight=1) 

self.root.columnconfigure(0, weight=1) 

#####Main Frame

self.main_frame = tk.Frame(self.root, bg="#1e1e2f") 

self.main_frame.grid(row=0, column=0, sticky="nsew") 

self.chat_display = tk.Text(self.main_frame, wrap=tk.WORD, bg="#2c2c3c", fg="#ffffff", 

font = ("Segoe UI", 10), state='disabled', padx=10, pady=10, border=0) 

self.chat_display.pack(fill=tk.BOTH, expand=True, padx=(10, 0), pady=10, side=tk.LEFT) 

self.scrollbar = tk.Scrollbar(self.main_frame, command=self.chat_display.yview) 

self.scrollbar.pack(fill=tk.Y, side=tk.RIGHT, pady=10) 

self.chat_display.config(yscrollcommand=self.scrollbar.set) 

    

    4. Input & Control Buttons


Just below the chat area is the input section, where users can type their messages. It’s built using an Entry widget styled with a dark theme to match the chat area. This field also listens for the Enter key so users can quickly send messages. Beside it, a row of buttons like Send, History, and Clear, provides additional controls. These buttons let users send messages, view the entire chat history in a pop-up, or clear the chat window entirely, offering a smooth and intuitive chatting experience.

####Input Frame

self.input_frame = tk.Frame(self.root, bg="#1e1e2f") 

self.input_frame.grid(row=1, column=0, sticky="ew", pady=(0, 10), padx=10) 

self.input_frame.columnconfigure(0, weight=1) 

self.user_input = tk.Entry(self.input_frame, font=("Segoe UI", 11), 

bg="#333347", fg="#ffffff", insertbackground="white", relief=tk.FLAT) 

self.user_input.grid(row=0, column=0, sticky="ew", padx=(0, 10), ipady=6) 

self.user_input.bind("<Return>", self.send_message) 

#####Buttons Frame

self.button_frame = tk.Frame(self.input_frame, bg="#1e1e2f") 

self.button_frame.grid(row=0, column=1, sticky="e") 

self.send_button = tk.Button(self.button_frame, text="Send", command=self.send_message, 

bg="#000000", fg="white", font=("Segoe UI", 10), activebackground="#45a049", width=8) 

self.send_button.pack(side=tk.LEFT, padx=2) 

self.history_button = tk.Button(self.button_frame, text="History", command=self.show_history, 

bg="#000000", fg="white", font=("Segoe UI", 10), activebackground="#1976D2", width=8) 

self.history_button.pack(side=tk.LEFT, padx=2) 

self.clear_button = tk.Button(self.button_frame, text="Clear", command=self.clear_chat, 

bg="#000000", fg="white", font=("Segoe UI", 10), activebackground="#d32f2f", width=8) 

self.clear_button.pack(side=tk.LEFT, padx=2)

#### Greeting

self.post_message("DialoGPT", random.choice([ 

"Hey there! What's on your mind today?",

"Hello! How can I help you?",

"Hi! Let's chat. What would you like to discuss?"

         ]))


     5. Messaging Handling & Interaction Flow:


To maintain the dynamic nature of the interaction, there are methods to post messages (post_message), to show history, and to delete (clear) the chat. When a message is submitted, a passing app will briefly display a typing indicator (using typing_indicator) for a short time. This additional delay gives a human-like timing to the response and makes the bot appear more human and less robotic. All messages are stored in a shared chat_log so that conversations can be recovered at any time.

def post_message(self, sender, message):

         self.chat_display.config(state='normal')

        tag = 'bot' if sender == "DialoGPT" else 'user'

        self.chat_display.insert(tk.END, f"{sender}: {message}\n", tag)

        self.chat_display.tag_config('bot', foreground='#9CDCFE')

        self.chat_display.tag_config('user', foreground='#CE9178')

        self.chat_display.see(tk.END)

         self.chat_display.config(state='disabled')

        chat_log.append(f"{sender}: {message}")

def show_history(self):

        history_text = "\n".join(chat_log)

        messagebox.showinfo("📜 Chat History", history_text)

def clear_chat(self):

         self.chat_display.config(state='normal')

        self.chat_display.delete('1.0', tk.END)

         self.chat_display.config(state='disabled')

        chat_log.clear()

def typing_indicator(self):

        typing_message = "DialoGPT: ...\n"

         self.chat_display.config(state='normal')

        self.chat_display.insert(tk.END, typing_message)

        self.chat_display.see(tk.END)

         self.chat_display.config(state='disabled')

        self.root.after(1500, self.generate_response)


       6. Generating Smart Responses


The magic, at generate_response(), goes to the part where the user input is encoded and passed to the DialoGPT model, which then does the reply/conversation-history-specific thing, which should be a lot more coherent and have a lot more turns than regular natural conversation. The model uses a couple of different techniques (temperature and top-p sampling) to make sure that the messages don't sound "choppy" and "stale," which is more "real" if they're from real users. After responding to a question, the bot sometimes gives you an informal prompt to keep it going so that the whole thing feels like you're talking to a real person.


def generate_response(self):

        global chat_history_ids, step

        user_input_text = self.user_input.get().strip()

        If not user_input_text:

            return


       7. Main Loop or Launch the App


The code snippet below is responsible for starting a Tkinter-based graphical user interface (GUI) application in Python. The line if __name__ == "__main__": ensures that the following block of code runs only when the script is executed directly, not when it is imported as a module in another script. Inside this block, root = tk.Tk() creates the main application window using Tkinter, which serves as the root of the GUI. Then, app = ChatApp(root) initializes an instance of the ChatApp class, passing the root window to set up the app’s layout and functionality. Finally, root.mainloop() enters Tkinter’s event loop, which waits for user interactions such as button clicks or key presses and updates the interface accordingly. This loop keeps the application running until the user closes the window.


if __name__ == "__main__":

root = tk.Tk()

app = ChatApp(root)

root.mainloop()

 

Example Usage

Chatbot:


 

Chat History:


 

Conclusion


This chatbot app is a great hands-on project for anyone curious about conversational AI and building user-friendly desktop applications. By blending Microsoft’s DialoGPT with a simple yet polished Tkinter interface, it delivers a fun and interactive chat experience right on your computer, no browser needed. It also highlights how powerful and approachable these advanced language models have become, especially with open-source platforms like Hugging Face making them so accessible.

Whether you're tinkering for fun, building a personal assistant, or prototyping a customer support bot, this project gives you a solid, scalable foundation to build on. It’s a great mix of creativity and functionality, with plenty of room to customize and expand.


References


https://huggingface.co/nari-labs/Dia-1.6B


Leave Your Comment