Skip to main content
Engineering LibreTexts

10.3: Canvas Widgets

  • Page ID
    15476
  • One of the most versatile widgets is the Canvas, which creates a region for drawing lines, circles and other shapes. If you did Exercise 15.9.1 you are already familiar with canvases.

    The method ca creates a new Canvas:

    canvas = g.ca(width=500, height=500)
    

    width and height are the dimensions of the canvas in pixels.

    After you create a widget, you can still change the values of the options with the config method. For example, the bg option changes the background color:

    canvas.config(bg='white')
    

    The value of bg is a string that names a color. The set of legal color names is different for different implementations of Python, but all implementations provide at least:

    white   black
    red     green    blue   
    cyan    yellow   magenta
    

    Shapes on a Canvas are called items. For example, the Canvas method circle draws (you guessed it) a circle:

    item = canvas.circle([0,0], 100, fill='red')
    

    The first argument is a coordinate pair that specifies the center of the circle; the second is the radius.

    Gui.py provides a standard Cartesian coordinate system with the origin at the center of the Canvas and the positive y axis pointing up. This is different from some other graphics systems where the origin is in the upper left corner, with the y axis pointing down.

    The fill option specifies that the circle should be filled in with red.

    The return value from circle is an Item object that provides methods for modifying the item on the canvas. For example, you can use config to change any of the circle’s options:

    item.config(fill='yellow', outline='orange', width=10)
    

    width is the thickness of the outline in pixels; outline is the color.

    Exercise \(\PageIndex{1}\)

    Write a program that creates a Canvas and a Button. When the user presses the Button, it should draw a circle on the canvas.

    • Was this article helpful?