Python Tkinter Canvas
The Python Tkinter Canvas widget, like the canvas in HTML5, is used for drawing. You can place graphics, text, widgets, or frames on the canvas.
Syntax
The syntax format is as follows:
w = Canvas ( master, option=value, ... )
-
master: The parent container of the button.
-
options: Optional items, i.e., the settable properties of the button. These options can be set in the form key = value and separated by commas.
| No. | Options & Description |
|---|---|
| 1 |
bd Border width, in pixels, defaulting to 2 pixels. |
| 2 |
bg Background color |
| 3 |
confine If true (the default), the canvas cannot be scrolled outside the scrollable region. |
| 4 |
cursor The shape of the cursor, such as arrow, circle, cross, plus, etc. |
| 5 |
height Height |
| 6 |
highlightcolor The color to use for highlighting |
| 7 |
relief Border style, with possible values FLAT, SUNKEN, RAISED, GROOVE, RIDGE. The default is FLAT. |
| 8 |
scrollregion A tuple (w, n, e, s) that defines the maximum scrollable area of the canvas, where w is the left, n is the top, e is the right, and s is the bottom. |
| 9 |
width The size of the canvas on the X axis. |
| 10 |
xscrollincrement The amount value used for a horizontal scroll request. |
| 11 |
xscrollcommand Horizontal scrollbar; if the canvas is scrollable, this property is the .set() method of the horizontal scrollbar. |
| 12 |
yscrollincrement Similar to xscrollincrement, but in the vertical direction. |
| 13 |
yscrollcommand Vertical scrollbar; if the canvas is scrollable, this property is the .set() method of the vertical scrollbar. |
The Canvas widget supports the following standard options:
arc - create an arc
coord = 10, 50, 240, 210
arc = canvas.create_arc(coord, start=0, extent=150, fill="blue")
image - create an image
filename = PhotoImage(file = "sunshine.gif")
image = canvas.create_image(50, 50, anchor=NE, image=filename)
line - create a line
line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, options)
oval - create a circle
oval = canvas.create_oval(x0, y0, x1, y1, options)
polygon - create a polygon with at least three vertices
oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn, options)
Example
In the example, clicking the button displays a message:
Example
#!/usr/bin/python
-- coding: UTF-8 --
import
Tkinter
import
tkMessageBox
-- coding: cp936 --
Create a rectangle, specifying the canvas color as white
from
Tkinter
import
root
=
Tk
(
)
Create a Canvas and set its background color to white
cv
=
Canvas
(
root
,
bg
=
'
white
'
)
Create a rectangle with coordinates (10,10,110,110)
cv
.
create_rectangle
(
10
,
10
,
110
,
110
)
cv
.
pack
(
)
root
.
mainloop
(
)
For clarity, set the background color to white to distinguish it from root
top
.
mainloop
(
)
The test output is as follows:
Python GUI Programming