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}\n\n"
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)}\n\n"
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)
CodePudding user response:
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.