Daijoubu
Daijoubu

Reputation: 63

How can i animate text by character in Tkinter?

So i know that in the python window you can use this..

for char in introstring:
    sleep(0.2)
    sys.stdout.write(char)
    sys.stdout.flush()

and it will display the text in the window, character by character at the speed of 0.2

How can I transition this into a Tkinter window? For example, I have the the text:

canvas.create_text((720,454),text="Just in case you start to feel sniffily, or something",fill="white", font=('arial'))

Is there a way to get the same animation but in the Tkinter GUI, I have set up? Ive heard something about the .after command, but I cant seem to find how it would apply for this.

Upvotes: 2

Views: 6476

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55469

Here's a very simple example that prints text character by character to a canvas, with a delay of 500 milliseconds between characters.

import Tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()

canvas_text = canvas.create_text(10, 10, text='', anchor=tk.NW)

test_string = "This is a test"
#Time delay between chars, in milliseconds
delta = 500 
delay = 0
for i in range(len(test_string) + 1):
    s = test_string[:i]
    update_text = lambda s=s: canvas.itemconfigure(canvas_text, text=s)
    canvas.after(delay, update_text)
    delay += delta

root.mainloop()

This code has been tested on Python 2.6. To run it on Python 3 you need to change the import statement to import tkinter as tk


Here's a more sophisticated example that displays text typed into an Entry widget. The text is shown when Enter is pressed in the Entry widget.

#!/usr/bin/env python

''' animate text in a tkinter canvas 

    See http://stackoverflow.com/q/34973060/4014959
    Written by PM 2Ring 2016.01.24
'''

import Tkinter as tk

class Application(object):
    def __init__(self):
        root = tk.Tk()
        self.canvas = tk.Canvas(root)
        self.canvas.pack()
        self.canvas_text = self.canvas.create_text(10, 10, text='', anchor=tk.NW)

        self.entry = tk.Entry(root)
        self.entry.bind("<Return>", self.entry_cb)
        self.entry.pack()
        root.mainloop()

    def animate_text(self, text, delta):
        ''' Animate canvas text with a time delay given in milliseconds '''
        delay = 0
        for i in range(len(text) + 1):
            update_text = lambda s=text[:i]: self.canvas.itemconfigure(self.canvas_text, text=s)
            self.canvas.after(delay, update_text)
            delay += delta

    def entry_cb(self, event):
        self.animate_text(self.entry.get(), 250) 

app = Application()

Upvotes: 4

Related Questions