tkinter not drawing shapes with negative points

Question:

This maybe a very stupid question but I am having some troubles with tkinter. I am very new to using tkinter and wanted to learn something during my free time which I don’t have much of. I have set up the canvas and everything but in a pickle when I try to dare a rectangle with negative points. I don’t kow why, it just doesn’t draw anything.

What I am trying to do is to draw a rectangle underneath one another.

I have attached the code below. It draws the rectangle which is filled with green, but when I try to draw the rectangle filled with red, nothing appears.

I really appreciate the help.

from tkinter import *

mainWindow = Tk()

drawingCanvas = Canvas(mainWindow, width=300, height=300)

drawingCanvas.pack()

drawingCanvas.create_rectangle(50, 25, 150, 75, fill="green")

drawingCanvas.create_rectangle(50, -200, 150, -100, fill="red")

mainloop()

I tried to plot the points using using a online plotter demos to check if the points are correct. It is, but whne I draw it in tkinter, the rectangle with negative points is missing/doesn’t get drawn.

Asked By: ba3sian

||

Answers:

The rectangle with negative points is not missing but is drown outside of the screen. A tkinter Canvas starts at 0/0 on the top left of the screen so negative numbers will be drawn outside the window.

Change:

drawingCanvas.create_rectangle(50, -200, 150, -100, fill="red")

To:

drawingCanvas.create_rectangle(50, 200, 150, 100, fill="red")
Answered By: Mike – SMT

The top-left corner of the canvas defaults to 0,0. Since your objects are being drawn above that coordinate they aren’t visible.

You can adjust the scrollregion after you’ve created the objects, and the canvas will be adjusted so that the top-left-most object is visible. You can do this with the following statement, which should come after you’ve created the items on the canvas:

drawingCanvas.configure(scrollregion=drawingCanvas.bbox("all"))

drawingCanvas.bbox("all") returns the bounding box of all of the items on the canvas. This is then passed into the configure method to change the scrollregion attribute of the canvas.

This works in this specific case since everything you draw will fit on the window. If you draw items far to the right or far below they won’t be visible. This is a convenient way to adjust the viewable portion of the canvas which, as a side effect, adjusts what is displayed in the upper-left corner.

screenshot

Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.