Drawing with tkinter module in Python (continued)

Keywords: Python REST React

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:

import 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.
Lateral movement of triangle

 

To extend, if we want the triangle to move along the diagonal line on the screen, we can do the eighth action:

import time
from tkinter import*
tk = Tk()
canvas = Canvas(tk,width=400,height=400)
canvas.pack()
canvas.create_polygon(10,10,10,60,50,35)  ##Create a triangle
for x in range(0,60):
    canvas.move(1,5,5)  ##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.
The triangle moves diagonally

 

If you want the triangle to go back diagonally to the beginning on the screen, use - 5, - 5 (add this code at the end)

import time
from tkinter import*
tk = Tk()
canvas = Canvas(tk,width=400,height=400)
canvas.pack()
canvas.create_polygon(10,10,10,60,50,35)  ##Create a triangle
for x in range(0,60):
    canvas.move(1,5,5)  ##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.
for x in range(0,60):
    canvas.move(1,-5,-5) 
    tk.update()             
    time.sleep(0.05)
Diagonal motion and return to initial position

 

 

11. Let the object react to the operation

We can use "message binding" to make the triangle react when someone presses a key.

To start processing events, we first need to create a function. When we tell tkinter to bind a particular function to (or relate to) a particular event, the binding is complete.

In other words, tkinter automatically calls this function to handle events.

For example, to move a triangle when you press the Enter key, we can define this function:

def movetriangle(event):
    canvas.move(1,5,0)

 

This function accepts only one parameter, which tkinter uses to pass information about events to the function. Now we use the bind_all function on canvas to tell tkinter that this function should be called when a particular event occurs. The code is as follows:

from tkinter import*
tk = Tk()
canvas = Canvas(tk,width=400,height=400)
canvas.pack()
canvas.create_polygon(10,10,10,60,50,35)
def movetriangle(event):
    canvas.move(1,5,0)
canvas.bind_all('<KeyPress-Return>',movetringle)  ##Let tkinter monitor the KeyPress event and call the movetriangle function when it occurs

 

 

So how do we change the direction of the triangle according to the different keys? For example, use the direction key.

We can try to change the movetriangle function:

def movetriangle(event):
    if event.keysym == 'up':
        canvas.move(1,0,-3)  ##The first parameter makes the ID number of the shape drawn on the canvas, the second is the value added to the x (horizontal) coordinate, and the third is the value added to the y (vertical) coordinate.
    elif event.keysym == 'down':
        canvas.move(1,0,3)
    elif event.keysym == 'left':
        canvas.move(1,-3,0)
    else
        canvas.move(1,3,0)

 

 

Finally, the code is summarized as follows:

from tkinter import*
tk = Tk()
canvas = Canvas(tk,width=400,height=400)
canvas.pack()
canvas.create_polygon(10,10,10,60,50,35)
def movetriangle(event):
    if event.keysym == 'Up':
        canvas.move(1,0,-3)  ##The first parameter makes the ID number of the shape drawn on the canvas, the second is the value added to the x (horizontal) coordinate, and the third is the value added to the y (vertical) coordinate.
    elif event.keysym == 'Down':
        canvas.move(1,0,3)
    elif event.keysym == 'Left':
        canvas.move(1,-3,0)
    else:
        canvas.move(1,3,0)
canvas.bind_all('<KeyPress-Up>',movetriangle)  ##Let tkinter monitor the KeyPress event and call the movetriangle function when it occurs
canvas.bind_all('<KeyPress-Down>',movetriangle)
canvas.bind_all('<KeyPress-Left>',movetriangle)
canvas.bind_all('<KeyPress-Right>',movetriangle)
Directional keys control the movement of triangles

 

 

12. More ways to use ID

As long as you use the function on the canvas that starts with create_it always returns an ID. This function can be used in other functions.

If we modify the code to save the return value as a variable and then use the variable, the code will work regardless of the return value:

>>> mytriangle = canvas.create_polygon(10,10,10,60,50,35)
>>> canvas.move(mytriangle,5,0)

 

We can use itemconfig to change the color of the triangle, which requires ID as the first parameter:

>>> canvas.itemconfig(mytrigle,fill='bue')  ##Change the fill color of the object whose ID is the value in mytriangle to blue

 

It can also give a triangle a contour line of different colors. The ID is also used as the first parameter.

>>> canvas.itemconfig(mytrigle,outline='red') 

 

 

 

summary

  1. Make a simple animation.
  2. Learned how to use event binding to get graphics to respond to keystrokes, which is very useful when writing computer games.
  3. How does a function that starts with create in tkinter return an ID number?

I have been studying Python for two days. At first, I thought it would be more convenient to write an animation or draw a figure with it, and the interface is beautiful. It's much better than the dos window in the black hole. I'm going to write a program to send a girl as a birthday gift (promised last year). After two days of learning, I slowly found the advantages of Python language, the most important thing is easy to learn, and can call various libraries.

I believe that my encounter with Python is just the beginning, and there is still a long way to go.

Posted by sandthipe on Sat, 23 Mar 2019 05:33:53 -0700