Comprends Le Css Canvas
Comprends Le Css Canvas
The canvas is probably the most interesting feature that Tkinter has. It allows you to draw shapes
in an almost free-form manner. Although the basic canvas commands are rather simple, they will
allow you to animate objects, which allow you to make fully functional games. Understanding
how to manipulate the canvas is absolutely essential before you can move on to bigger and better
projects.
If we wanted our Tkinter window to have only one canvas of height and width 300, the code we
would write would look like this:
We declared canvas as a global variable because we will want to be able to access it in the
function we make later.
Other objects that you can draw in Tkinter include ovals, lines, and text. A full list appears
online.
Binding keystrokes:
If we want one of the widgets we created in Tkinter to do something whenever we press a key,
we must bind that key to that widget. The syntax for binding a keystroke is:
foo.bind(event,handler)where foo is the widget, event is the name of the key, and
handler is the function that we want to call when we press that key. The function should take
no parameters other than event.
If we wanted to draw a square on the canvas whenever we pressed the space bar, our code would
look something like this:
from Tkinter import *
root = Tk()
foo = Canvas(root, height = 300, width = 300)
def drawSquare(event):
global foo
foo.create_rectangle(100,100,200,200,fill = "red")
foo.pack()
root.bind("<Space>",drawSquare)