user14959776
user14959776

Reputation:

Delaying parts of text being inserted into Scroll Text Box (scrolledtext)

I have a button which inserts text into a 'scrolltext' box when it is clicked.

I want to delay parts of the text being inserted into the text box. As in, one line of text is insert, there a 3 second delay, the next line of text is inserted and so on...

The I attempted using 'time' to make this work. However, this just delays all the text being inserted by the combined value and then all the text is inserted at once. Is there a way to make it work how I wish? And is it possible to delay it, so that each letter is inserted one at a time?

This is a much simplified version of what I've tried:

import tkinter as tk
from tkinter import *
from tkinter import scrolledtext
import time

# This is the GUI
trialGUI = Tk()
trialGUI.geometry('710x320')
trialGUI.title("Test GUI")

#This is the text that should be inserted when the button is pressed
def insertText():
    trialBox.insert(tk.INSERT, 'This line should be inserted first.\n')
    time.sleep(1)
    trialBox.insert(tk.INSERT, 'This line should be inserted after a 1 second delay.\n')
    time.sleep(3)
    trialBox.insert(tk.INSERT, 'This line should be inserted after a 3 second delay.\n')
    time.sleep(3)
    trialBox.insert(tk.INSERT, 'This line should be inserted after a 3 second delay.\n')

#This is the scrolling text box
trialBox = scrolledtext.ScrolledText(trialGUI, wrap = tk.WORD, width = 42, height = 10, font=(14))
trialBox.grid(row = 0, column = 0, columnspan = 4, pady = 3)

#This button runs the code to insert the text
trialButton = Button(trialGUI, text = "Run Code", command = insertText)
trialButton.grid(row = 1)

trialGUI.mainloop()

Upvotes: 0

Views: 361

Answers (1)

Henry
Henry

Reputation: 3942

Here's a solution using the .after() method:

def insertText():
    global previousDelay
    previousDelay = 0
    delayedInsert('This line should be inserted first.\n',0)
    delayedInsert('This line should be inserted after a 1 second delay.\n',1)
    delayedInsert('This line should be inserted after a 3 second delay.\n',3)
    delayedInsert('This line should be inserted after a 3 second delay.\n',3)

def delayedInsert(text, delay):
    global previousDelay
    trialGUI.after((delay + previousDelay) * 1000, lambda: trialBox.insert(tk.INSERT,text))
    previousDelay += delay

It uses a delayedInsert function which takes the text and delay in seconds and the global variable previousDelay to make the delays appear asynchronous (they are still happening at the same time but the delays are changed to make it appear like they are not). If the delays were not changed, each delay would start at the same time, not one after the other. The delayedInsert function waits for the delay specified plus the previous delay before inserting the text. This gives the same effect as time.sleep() but it works with Tkinter.

Upvotes: 1

Related Questions