I'm trying to use CustomTkinter to create a game, and I want to make the text in a CTkLabel be slowly printed out, one character at a time. I want the effect of seeing text appear as if a person was typing it out in real time. Most of the resources I found are for Tkinter, so I'm not sure how to do this.
This is part of the code I'm struggling with:
dialogue_var = ("Hello User")
dialogue_var = ("Ready To Protect It")
dialogue = customtkinter.CTkLabel(app, width=350, height=80, text=dialogue_var)
dialogue.pack(padx=1, pady=1)
DirkS posted the following print_slow function in the Raspberry Pi forums:
from time import sleep def print_slow(txt): # cycle through the text one character at a time for x in txt: # print one character, no new line, flush buffer print(x, end='', flush=True) sleep(0.3) # go to new line print() print_slow("Hello. I'm feeling a bit slow today")
but I don't know how to implement it with a CTkLabel. It just keeps saying that the command wasn't closed.
Here's a solution in pure Tkinter. Based on my understanding from the docs, you should be able to just replace class names from Tkinter with CTkinter.
In case you aren't familiar with event-driven applications, the TkDocs tutorial offers this quick introduction:
In other words, something like
won't work because that
sleepcall will repeatedly pause execution, preventing the event loop from doing its thing; the app would be almost completely unresponsive.Instead, we need to set up structures that can work in small, discrete steps based on timers. First, a couple imports:
Now we define a custom
StringVarclass. This will let us add to a string character by character. Each time thestepmethod is called, a character gets moved from the buffer to the end of the displayed string:Now we define a class that will repeatedly invoke callback functions like
TeletypeVar.stepat a steady pace. It also has astepmethod, which invokes the assigned callback function, and starts the timer for its own next step:That takes care of the prep work. Creating the frame and starting the main loop should look familiar:
I wrote this in a way that will hopefully make it easy to play around with the different parts to see how everything works. If anything is unclear, just let me know.
Disclaimer: I haven't worked with Tkinter or CustomTkinter before. This is all based on quickly skimming the docs and similarity to many other event-driven toolkits, so this might not be the most elegant solution.