0

i'am trying to align the user input on right side (using tkinter python) in scrolledtext and chatbot's output on left side but no success. also the text beckground should have light color. i mean it should be just look like messanger or other messaging platform where both sides have different sides and sometimes colors. please help me its a part of my final year project. m very worried about it. here is my code:

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os
import tkinter as tk
try:
    import ttk as ttk
    import ScrolledText
except ImportError:
    import tkinter.ttk as ttk
    import tkinter.scrolledtext as ScrolledText
import time


class TkinterGUIExample(tk.Tk):

    def __init__(self, *args, **kwargs):
        """
        Create & set window variables.
        """
        tk.Tk.__init__(self, *args, **kwargs)

        self.chatbot = ChatBot(
            "GUI Bot",
            storage_adapter="chatterbot.storage.SQLStorageAdapter",
            logic_adapters=[{
                'import_path': 'chatterbot.logic.BestMatch',
                'default_response': 'I am sorry, but I do not understand.',
                'maximum_similarity_threshold': 1.0
} ]
        )


        for files in os.listdir('C:/Users/HP/Desktop/FYP BOT/training_data/'):
            con=open('C:/Users/HP/Desktop/FYP BOT/training_data/'+files,'r').readlines()
            trainer = ListTrainer(self.chatbot)
            trainer.train(con)
        self.title("Chatterbot")

        self.initialize()

    def initialize(self):
        """
        Set window layout.
        """
        self.grid()

        ttk.Style().configure("TButton", padding=6, relief="flat",background="#ccc")
        style = ttk.Style()
        style.map("C.TButton",
            foreground=[('pressed', 'red'), ('active', 'blue')],
            background=[('pressed', '!disabled', 'black'), ('active', 'white')]
            )


        self.respond = ttk.Button(self, text='Get Response', command=self.get_response,style="C.TButton")
        self.respond.grid(column=1, row=2, sticky='nesw', padx=3, pady=10)


        self.usr_input = tk.Entry(self, state='normal',text='Enter your query here!')
        self.usr_input.grid(column=0, row=2, sticky='nesw', padx=1, pady=5)


        self.conversation_lbl = tk.Label(self, anchor=tk.E, text='Conversation',font=('Arial Bold Underline',18),bg="#f89406",fg="#feffff")
        self.conversation_lbl.grid(column=0, row=0,columnspan=2, padx=3, pady=3)

        self.conversation = ScrolledText.ScrolledText(self,
                                                      state='disabled',borderwidth=5,
                                                      highlightthickness=1,
                                                      bg='#15202b',fg='#ffffff',
                                                      font=('Arial Bold',8))
        self.conversation.grid(column=0, row=1, columnspan=2, sticky='nesw', padx=3, pady=3)


    def get_response(self):
        """
        Get a response from the chatbot and display it.
        """
        user_input = self.usr_input.get()
        self.usr_input.delete(0, tk.END)

        response = self.chatbot.get_response(user_input)

        self.conversation['state'] = 'normal'
        self.conversation.insert(
            tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(response.text) + "\n"
        )
        self.conversation['state'] = 'disabled'

        time.sleep(0.5)


gui_example = TkinterGUIExample()
gui_example.geometry('930x600+10+10')
gui_example.configure(background='#3a8fc5')
gui_example.mainloop()
  • to align probably you would have to add spaces - and you have to calculate on your own how many spaces to add. – furas Dec 14 '19 at 11:21
  • check also `tags` with `justify` [How to set justification on Tkinter Text box](https://stackoverflow.com/questions/15014980/how-to-set-justification-on-tkinter-text-box) – furas Dec 14 '19 at 11:24

1 Answers1

2

You can use tags to assign properties to part of text.

Using justify you can have text on right side but all lines will be aligned to the right.

import tkinter as tk 
import tkinter.scrolledtext as ScrolledText

root = tk.Tk()
#text_widget = tk.Text()
text_widget = ScrolledText.ScrolledText()
text_widget.pack(fill='both', expand=True)

text_widget.tag_configure('tag-center', justify='center')
text_widget.tag_configure('tag-left', justify='left')
text_widget.tag_configure('tag-right', justify='right')

text_widget.insert('end', 'Hello\nWorld!!!\n', 'tag-center')
text_widget.insert('end', 'Hello\nWorld!!!\n', 'tag-left')
text_widget.insert('end', 'Hello\nWorld!!!\n', 'tag-right')

root.mainloop()

enter image description here

For better control you would try to use Canvas with Labels and Scrollbar


EDIT: Using window_create you can add Label to ScrolledText and using previous tag you can move it to the right. And then you can change Label - color, margin (padx, pady), etc. You may try to add Label with image or even Frame to put more different widgets.

import tkinter as tk 
import tkinter.scrolledtext as ScrolledText

root = tk.Tk()
#text_widget = tk.Text()
text_widget = ScrolledText.ScrolledText()
text_widget.pack(fill='both', expand=True)

label1 = tk.Label(text_widget, text="Hello\nWorld!!!", background='#d0ffff', justify='left', padx=10, pady=5)
label2 = tk.Label(text_widget, text="Hello\nWorld!!!", background='#ffffd0', justify='left', padx=10, pady=5)
label3 = tk.Label(text_widget, text="Hello\nWorld!!!", background='#d0ffff', justify='left', padx=10, pady=5)

text_widget.tag_configure('tag-left', justify='left')
text_widget.tag_configure('tag-right', justify='right')


text_widget.insert('end', '\n')
text_widget.window_create('end', window=label1)

text_widget.insert('end', '\n ', 'tag-right') # space to move Label to the right 
text_widget.window_create('end', window=label2)

text_widget.insert('end', '\n')
text_widget.window_create('end', window=label3)

root.mainloop()

enter image description here

furas
  • 134,197
  • 12
  • 106
  • 148
  • thanks a lottttttttttttttttt but could you please help me to complete it i mean how can i implement it in my code because i tried a lot by using your answer but it still gives me error.its a part of my final year project and m beginner so if you will run on ur system and give me answer i'll be veryyyyyyyyyy thankful to you – Hassan Sheraz Basra Dec 15 '19 at 10:38