[Tutor] Canvas Widget
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue Apr 15 14:48:13 2003
On Mon, 14 Apr 2003, Diego Prestes wrote:
> Im trying to use canvas in tkinter but when I put the widget it
> always stay in the top of the program. I try to make a frame with the
> side=TOP to put the buttons of the toolbar but it stay in bottom.
>
> Someone know if I can change the side of the canvas?
Hi Diego,
Tkinter's default "packing" layout system is a little bit weird at first,
so let's go through a small example; it might help clear things up.
If you want to make something like:
+-----------------+---------+
| | |
| | Button1 |
| |---------+
| Canvas | |
| | Button2 |
| |---------+
| | |
| | Button3 |
+-----------------+---------+
To construct something like this, we can think of it as two pieces, a
canvas on the left hand side,
+-----------------+
| |
| |
| Canvas |
| |
| |
| |
| |
| |
+-----------------+
plus a frame of buttons on the right hand side:
+---------+
| |
| Button1 |
|---------+
| |
| Button2 |
|---------+
| |
| Button3 |
+---------+
Here's some example Tkinter code that constructs a window like this:
###
>>> import Tkinter
>>> root = Tkinter.Tk()
>>> canvas = Tkinter.Canvas(root)
>>> canvas.pack(side=Tkinter.LEFT)
>>> button_frame = Tkinter.Frame(root)
>>> button_frame.pack(side=Tkinter.RIGHT)
>>> b1, b2, b3 = (Tkinter.Button(text="Button1"),
... Tkinter.Button(text="Button2"),
... Tkinter.Button(text="Button3"))
>>> b1.pack(side=Tkinter.TOP)
>>> b2.pack(side=Tkinter.TOP)
>>> b3.pack(side=Tkinter.TOP)
###
The order of packing can matter: you may want to experiment with your
interactive interpreter to see what happens if we pack the button_frame to
the LEFT first, and then the canvas.
> and other question. Someone know how can I create a rectangle, for
> example, using the mouse?
You may want to look at Fredrik's tutorial on Tkinter:
http://www.pythonware.com/library/tkinter/introduction/
In particular, if we look at the Canvas documentation:
http://www.pythonware.com/library/tkinter/introduction/x2102-methods.htm
we can see a method called "create_rectangle" that takes a "bounding box".
Here's an example call to create_rectangle:
###
>>> canvas.create_rectangle(((10, 10), (20, 20)))
1
###
A gloriously puny rectangle should show up on the upper left hand corner
of the canvas. *grin*
To do drawing with a mouse, you may need to read a little bit about "event
handling". Here's a link to the Events section of Tkinter tutorial:
http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
Please feel free to ask questions on Tutor; we'll be happy to help clear
up the confusing parts. Good luck!