Search code examples
pythonpython-3.xtkinterchatterbot

Auto-update label with the pressing of a tkinter button


I'm trying to create a chatbot program with CHATTERBOT MODULE and TKINTER. It's almost ok, in fact my problem is that every button-click, the program creates me new labels, with command risposta.pack(). My intent is creating just one label and update it every other button-click. How can I do it?

MY CODING:

from chatterbot import ChatBot
from tkinter import *
import time
from chatterbot.trainers import ListTrainer



bot = ChatBot(
"GUI Bot",
    storage_adapter="chatterbot.storage.SQLStorageAdapter",
    input_adapter='chatterbot.input.VariableInputTypeAdapter',
    output_adapter='chatterbot.output.OutputAdapter',
    database='../database,db',
    logic_adapters=[
        {
            "import_path": "chatterbot.logic.BestMatch",
            "statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
            "response_selection_method": "chatterbot.response_selection.get_first_response"
        }
    ]
)
with open('/home/griguols/Scrivania/chatterbot/istruzioni.txt') as istruzioni:
    conversation = istruzioni.readlines()
    bot.set_trainer(ListTrainer)
    bot.train(conversation)


def command():
    global risposta
    user_input = input.get()
    response = bot.get_response(user_input)
    risposta = Label(schermata, text=str(response.text))
    risposta.pack()





schermata = Tk()
ment = StringVar()

schermata.geometry('1000x500')
schermata.title('OMERO')

titolo = Label(schermata,text='OMERO')
titolo.pack()

input = Entry(schermata,textvariable=ment)
input.pack()



bottone = Button(schermata,text='PARLA CON OMERO',command=command)
bottone.pack()






schermata.mainloop()

Solution

  • To solve this issue, you can pack the label (only one time) after the button, so the last part of the code would look as follows:

    bottone = Button(schermata,text='PARLA CON OMERO',command=command)
    bottone.pack()
    
    risposta = Label(schermata, text="")
    risposta.pack()
    
    schermata.mainloop()
    

    Then, change the command function so that it only updates the text of the already packed label:

    def command():
        global risposta
        user_input = input.get()
        response = bot.get_response(user_input)
        risposta['text']=str(response.text)
    

    PS: I could not execute the with scope since you have not provided the .txt file. For you next post, please consider providing an MCVE.