Use the tkinter module in Python to plot (continued), pythontkinter

Source: Internet
Author: User

Use the tkinter module in Python to plot (continued), pythontkinter
8. display text

UseCreate_textWrite on the canvas. This function only requires 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')

 

Create_text FunctionThere are also several useful parameters, such as the font color. In the following code, we use coordinates (130,120) when calling the create_text function, as well as the text to be displayed and the red fill color:

canvas.create_text(130,120,text='Happy birthday to you!',fill='red')

 

We can also specify a font by providing a tuple containing the font name and font size. For example, if the size is 20, the Times font 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 images

To use tkinter to display an image on the canvas, first load the image, and then useCreate_image Function.

Here is an image on my elastic drive:

In this example, we can display the one.gif image:

>>> 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 image into the variable my_image. Coordinates (0, 0)/(50, 50) are the positions where the image is to be displayed. anchor = NW allows the function to use the upper left corner (North West) as the starting point of the painting, the last named parameter image points to the mounted image.

 

Note: Only GIF images can be installed with tkinter, and A. GIF image file can also be expanded.

To display other types of images, such as PNG and JPG, you need to use other modules, such as the Python Image Library.

 

 

10. create basic animations

Create a color-filled triangle to move it horizontally on the screen:

Import timefrom 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 (, 0) # move any painted object to the position tk that adds the x and y coordinates to the specified value. update () ## force tkinter to update the screen (redraw) time. sleep (0.05) # Let the program rest for 1/20 seconds (0.05 seconds), and then continue
Horizontal triangle Movement

 

If you want to move the triangle along the diagonal line on the screen, you can perform the following 8th actions:

Import timefrom 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 (, 5) # move any painted object to the position tk that adds the x and y coordinates to the specified value. update () ## force tkinter to update the screen (redraw) time. sleep (0.05) # Let the program rest for 1/20 seconds (0.05 seconds), and then continue
The triangle moves along the diagonal line.

 

If you want a triangle to return to the starting position along the diagonal line on the screen, use-5,-5 (add this code at the end)

Import timefrom 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 (, 5) # move any painted object to the position tk that adds the x and y coordinates to the specified value. update () ## force tkinter to update the screen (redraw) time. sleep (0.05) # Let the program rest for 1/20 seconds (0.05 seconds), and then continue for x in range (): canvas. move (1,-5,-5) tk. update () time. sleep (0.05)
Diagonal motion and return to initial position

 

 

11. Let the object respond to the operation

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

To start processing events, we must first create a function. The binding is completed when we tell tkinter to bind a specific function to (or associate with) a specific event.

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 only accepts one parameter (event), and tkinter uses it to pass event information to the function. Now we useBind_all FunctionTo tell tkinter to call this function when a specific 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. When this event occurs, call the movetriangle function.

 

 

So how can we change the direction of the triangle Based on Different buttons? For example, use a direction key.

We can try to change the movetriangle function:

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

 

 

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 (,-3) # The first parameter indicates the ID number of the Shape drawn on the canvas, and the second parameter indicates the value added to the x (horizontal direction) coordinate, the third is the elif event value added to y (vertical direction) coordinates. keysym = 'low': 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 KeyPress events. When this event occurs, call the movetriangle function canvas. bind_all ('<KeyPress-Down>', movetriangle) canvas. bind_all ('<KeyPress-Left>', movetriangle) canvas. bind_all ('<KeyPress-Right>', movetriangle)
Arrow keys control the movement of triangles

 

 

12. More methods for using ID

As long as the canvas is usedCreate _It always returns an ID. This function can be used in other functions.

If we modify the code to save the returned value as a variable and then use this variable, this code can work regardless of the returned value:

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

 

We can useItemconfigTo change the color of the triangle, ID must be used as the first parameter:

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

 

You can also give the triangle a contour line of different colors. Similarly, ID is used as the first parameter:

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

 

 

 

Summary

I have been learning Python for two days. I first thought that it is more convenient to use it to write an animation or draw a graph, and the interface is beautiful, which is much better than the dos window with a black hole, prepare to write a program to give a girl a birthday gift (promised last year ). After these two days of study, I gradually realized the advantages of the Python language. The most important thing is that it is easy to learn and can call various libraries.

I believe that my encounter with Python is just the beginning, and the road to it is still very long.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.