Move Text from right to left in Tkinter
Hey folks, This tutorial will help you move text on canvas from right to left. So for this project, we are going to use an in-built library of python namely: Tkinter
from tkinter import *
We’ll kick off with learning the functions used in this project:
The Shift() function:
def shift(): x1,y1,x2,y2 = canvas.bbox("marquee") if(x2<0 or y1<0): x1 = canvas.winfo_width() y1 = canvas.winfo_height()//2 canvas.coords("marquee",x1,y1) else: canvas.move("marquee", -2, 0) canvas.after(1000//fps,shift)
In the above shift() function, we get the coordinates of the text and move it 2 places in the negative X direction, if the text end reaches the frame boundaries then its coordinates are reset to the width and 50% of the height of the canvas. The shift() function is recursively called. We use the .after() method of Tkinter rather than use threading to register a callback.
In the main program we follow the following steps:
- We define the tk window using Tk() as the root variable.
- Then we create the title of the window.
- Next, we create a Canvas with some background color.
- Then we define a variable to store the text to be displayed.
- In the next step, we use .create_text() method of the Canvas class to create text on the canvas, whilst also passing parameters of the method.
Note: we define the initial coordinates of the text out of the canvas, this is then handled by the shift() function.
- In the former step, we pass a parameter ‘tag‘(without the quotes) in which we pass a tuple that contains aliases for the text.
- Then we find the position of the text on the canvas.
- With the help of those coordinates, we alter the size of the canvas.
- In this step, we define the fps variable(Note: FPS plays a major role in animation).
- Finally, we call the shift() function, which is responsible for the animation.
- We end by a root.mainloop() function to keep the events on the main window active and all widgets interactive.
The whole program to move text from right to left in Tkinter looks like so:
from tkinter import * def shift(): x1,y1,x2,y2 = canvas.bbox("marquee") if(x2<0 or y1<0): #reset the coordinates x1 = canvas.winfo_width() y1 = canvas.winfo_height()//2 canvas.coords("marquee",x1,y1) else: canvas.move("marquee", -2, 0) canvas.after(1000//fps,shift) ############# Main program ############### root=Tk() root.title('Move Text') canvas=Canvas(root,bg='black') canvas.pack(fill=BOTH, expand=1) text_var="Hey there Delilah!,What's it like in New York City." text=canvas.create_text(0,-2000,text=text_var,font=('Times New Roman',20,'bold'),fill='white',tags=("marquee",),anchor='w') x1,y1,x2,y2 = canvas.bbox("marquee") width = x2-x1 height = y2-y1 canvas['width']=width canvas['height']=height fps=40 #Change the fps to make the animation faster/slower shift() root.mainloop()
To learn more about Tkinter: