Drawing with the Tkinter module in Python (cont.)

Source: Internet
Author: User

Eight, display text

Write on the canvas with create_text . This function requires only two coordinates (the position of the text x and y), and a named parameter to accept the text to be displayed. For example:

 from 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, and so on. In the following code, we use the coordinates (130,120) when we call 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 giving a tuple that contains the font name and font size. For example, a 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   ",") "

Nine, display pictures

To display a picture on the canvas with Tkinter, first load the picture, and then use the create_image function on the canvas object.

This is a picture of my existence on the E disk:

We can show one.gif pictures like this:

 from 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)  

In line fifth, load the picture into the variable my_image. Coordinates (0,0)/(50,50) is where we want to display the picture, ANCHOR=NW let the function use the upper-left corner (northwest Northwest side) as the starting point for the drawing, and the last named parameter image points to the loaded picture.

Note: Only GIF images can be loaded with Tkinter, which is a picture file with a. gif extension.

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

X. Creating a basic animation

Create a color-filled triangle to move sideways on 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) #   #创建三角形  for  x Span style= "COLOR: #0000ff" >in  range (0,60 1,5,0) #   #把任意画好的对象移动到把x和y坐标增加给定值的位置  tk.update () #   #强制tkinter更新屏幕 (redraw)  time.sleep (0.05) #   #让程序休息二十分之一秒 (0.05 seconds), and then continue  
triangular transverse movement

To extend, if you want the triangle to move diagonally across the screen, we can act 8th:

 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) #   #创建三角形  for  x Span style= "COLOR: #0000ff" >in  range (0,60 1,5,5) #   #把任意画好的对象移动到把x和y坐标增加给定值的位置  tk.update () #   #强制tkinter更新屏幕 (redraw)  time.sleep (0.05) #   #让程序休息二十分之一秒 (0.05 seconds), and then continue  
The triangle moves diagonally

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

Import Time fromTkinterImport*tk=Tk () canvas= Canvas (tk,width=400,height=400) Canvas.pack () Canvas.create_polygon (10,10,10,60,50,35)##创建三角形 forXinchRange (0,60): Canvas.move (1,5,5)##把任意画好的对象移动到把x和y坐标增加给定值的位置Tk.update ()##强制tkinter更新屏幕 (re-painting)Time.sleep (0.05)##让程序休息二十分之一秒 (0.05 seconds) before continuing forXinchRange (0,60): Canvas.move (1,-5,-5) tk.update () Time.sleep (0.05)
diagonal movement and back to the initial position

Xi. let the object react to the operation

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

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

In other words, Tkinter will automatically call this function to handle the event.

For example, to have a triangle move when you press ENTER, we can define this function:

def Movetriangle (Event):    canvas.move (1,5,0)

This function takes only one argument (event) and Tkinter uses it to pass information about the event to the function. Now let's 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 Import*== 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)  # #让tkinter监视KeyPress事件, the Movetriangle function is called when the event occurs

So how do we change the direction of the triangle according to the different keys? Use the arrow keys, for example.

We can try to change the Movetriangle function:

defMovetriangle (event):ifEvent.keysym = =' up': Canvas.move (1,0,-3)##第一个参数使画布上所画的形状的ID数字, the second is the value of the X (horizontal) coordinate increment, and the third is the value of the Y (vertical direction) coordinate increment    elifEvent.keysym = =' Down': Canvas.move (1,0,3)    elifEvent.keysym = =' Left': Canvas.move (1,-3, 0)ElseCanvas.move (1,3,0)

The final code is summarized together as:

 fromTkinterImport*tk=Tk () canvas= Canvas (tk,width=400,height=400) Canvas.pack () Canvas.create_polygon (10,10,10,60,50,35)defMovetriangle (event):ifEvent.keysym = =' up': Canvas.move (1,0,-3)##第一个参数使画布上所画的形状的ID数字, the second is the value of the X (horizontal) coordinate increment, and the third is the value of the Y (vertical direction) coordinate increment    elifEvent.keysym = =' Down': Canvas.move (1,0,3)    elifEvent.keysym = =' Left': Canvas.move (1,-3, 0)Else: Canvas.move (1,3, 0) Canvas.bind_all ('<KeyPress-Up>', Movetriangle)##让tkinter监视KeyPress事件, the Movetriangle function is called when the event occursCanvas.bind_all ('<KeyPress-Down>', Movetriangle) Canvas.bind_all ('<KeyPress-Left>', Movetriangle) Canvas.bind_all ('<KeyPress-Right>', Movetriangle)
arrow keys to control the movement of triangles

12. More ways to use IDs

It always returns an ID if it uses a function that starts with Create_ on the canvas. This function can be used in other functions.

If we modify the code to save the return value as a variable and then use that 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 the ID as the first parameter:

>>> canvas.itemconfig (mytrigle,fill='bue')  ## Change the fill color of the object with the value in the variable Mytriangle to blue

You can also give the triangle a different color contour line, the same applies to the ID as the first parameter:

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

Summarize
    1. Made a simple animation.
    2. learned how to use event bindings to make graphics respond to keystrokes, which is useful when writing computer games.
    3. The function that starts with create in Tkinter is how to return an ID number.

have been learning python for two days, the first is to think of it is to use it to write an animation or draw a graphic more convenient, and the interface beautiful, than dark DOS window much better, ready to write a program to send a girl as a birthday gift (last year promised good). After two days of study, I slowly discovered the advantages of Python language, its most important is easy to learn, and can call various libraries.

I believe my encounter with Python is just beginning, and the road behind it is a long and long way.

Drawing with the Tkinter module in Python (cont.)

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.