8. Display Text
Write on the canvas with create_text. This function only needs two coordinates (the position of the text x and y) and a named parameter to accept the text to be displayed. For example:
>>> from tkinter import* >>> tk = Tk() >>> canvas = Canvas(tk,width=400,height=400) >>> canvas.pack() >>> canvas.create_text(150,100,text='Happy birthday to you')
The create_text function also has several useful parameters, such as font color. In the following code, we call the create_text function using coordinates (130, 120), text to display, and red filler colors:
canvas.create_text(130,120,text='Happy birthday to you!',fill='red')
We can also specify fonts by giving a tuple containing the font name and font size. For example, the Times font size of 20 is ('Times',20):
>>> canvas.create_text(150,150,text='Happy birthday',font=('Times',15)) >>> canvas.create_text(200,200,text='Happy birthday',font=('Courier',22)) >>> canvas.create_text(220,300,text='Happy birthday',font=('Couried',30))
9. Display pictures
To display a picture on a canvas with tkinter, first load the picture, and then use the create_image function on the canvas object.
This is a picture I have on disk E:
We can display one.gif pictures in this way:
>>> from tkinter import* >>> tk = Tk() >>> canvas = Canvas(tk,width=400,height=400) >>> canvas.pack() >>> my_image = PhotoImage(file='E:\\FFOutput\\one.gif') >>> canvas.create_image(0,0,anchor = NW,image = my_image) >>> canvas.create_image(50,50,anchor = NW,image = my_image)
In the fifth line, load the picture into the variable my_image. The coordinates (0,0)/(50,50) are where we want to display the image. anchor=NW lets the function use the upper left corner (northwest) as the starting point of the drawing, and the last named parameter image points to the loaded image.
Note: Only GIF images can be loaded with tkinter, that is, image files with the extension of. gif.
To display other types of pictures, such as PNG and JPG, you need to use other modules, such as the Python image library.
10. Creating Basic Animation
Create a colored triangle that moves horizontally across the screen:
Lateral movement of triangleimport time from tkinter import* tk = Tk() canvas = Canvas(tk,width=400,height=200) canvas.pack() canvas.create_polygon(10,10,10,60,50,35) ##Create a triangle for x in range(0,60): canvas.move(1,5,0) ##Move arbitrarily drawn objects to positions where x and y coordinates are added to a given value tk.update() ##Force tkinter to update the screen (redraw) time.sleep(0.05) ##Let the program rest for one-twentieth of a second (0.05 seconds) before continuing.