Python 2.6 Graphics Cookbook
上QQ阅读APP看书,第一时间看更新

Simple text

This is how to place text onto your canvas.

How to do it...

  1. In a text editor, type the code given in the following code.
  2. Save this as a file named text_1.py, inside the directory called constr again.
  3. As before, open up an X terminal or DOS window if you are using MS Windows.
  4. Change directory into constr - where text_1.py is located.
  5. Type text_1.py and your program should execute.
    # text_1.py
    #>>>>>>>>>>
    from Tkinter import *
    root = Tk()
    root.title('Basic text')
    cw = 400                                      # canvas width
    ch = 50                                      # canvas height
    canvas_1 = Canvas(root, width=cw, height=ch, background="white")
    canvas_1.grid(row=0, column=1)                              
    
    xy = 150, 20
    canvas_1.create_text(xy, text=" The default text size looks \ about 10.5 point")
    root.mainloop()

How it works...

The results are given in the following screenshot:

How it works...

Placing text exactly where you want it on a screen can be tricky because of the way font height and inter-character spacing as well as the text window dimensions all interfere with each other. You will probably have to spend a bit of time experimenting to get your text as you want it.

There's more...

Text placed onto a canvas offers a useful alternative to the often used print function as a debugging tool. You can send the values of many variables for display onto a canvas and watch their values change.

As will be demonstrated in the chapter on animation, the easiest way of observing the interaction of complex numerical relationships is to animate them in some way.