why is tkinter class functions only executed simultaneously?

Question:

i have created a small interface for a chatbot. When a text is entered the function "_on_enter_pressed()" is executed, this in turn executes two other functions, one to insert the text from the user into the textbox and the other the text from the bot into the textbox. In between I wanted to have a pause of about 0.5 seconds. Unfortunately both texts appear after 0.5 seconds at the same time and I can’t explain why.

  def _on_enter_pressed(self, event):
        msg = self.msg_entry.get()
        self._insert_message_user(msg, "You")
        time.sleep(0.5)
        self._insert_message_bot(msg, "Bot")

    def _insert_message_user(self, msg, sender):
        if not msg:
            return

        self.msg_entry.delete(0, END)
        msg1 = f"{sender}: {msg}nn"
        self.text_widget.configure(state=NORMAL)
        self.text_widget.insert(END, msg1)
        self.text_widget.configure(state=DISABLED)
        self.text_widget.see(END)

    def _insert_message_bot(self, msg, sender):
        msg2 = f"{sender}: {chat(msg, ChatApp.index)}nn"
        self.msg_entry.delete(0, END)
        self.text_widget.configure(state=NORMAL)
        self.text_widget.insert(END, msg2)
        self.text_widget.configure(state=DISABLED)
        self.text_widget.see(END)
Asked By: kaan46

||

Answers:

When you call sleep, it does just that: it puts the entire application to sleep. That includes putting to sleep the ability to update the display. Your app will be frozen for the duration of the call to sleep.

If you want something to happen after a delay, schedule the call with tkinter’s universal method after. It takes a number of milliseconds and a command as arguments. Positional arguments for the command can also appear as arguments.

In your case, change this code:

time.sleep(0.5)
self._insert_message_bot(msg, "Bot")

… with this code:

    self.after(500, self._insert_message_bot, msg, "Bot")

The above code will push the method self.insert_message_bot onto a queue to be processed in 500ms. When the function is called, it will be passed msg and "Bot" as arguments.

Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.