24

In python, tkinter, I'm trying to make a game that involves creating shapes onto a canvas. For example, I want a red rectangle to appear over my canvas image. When I execute my code, the rectangle you see is about 1 pixel in size, and I'm not sure why and how it got like that. Here's my code:

from tkinter import *
root = Tk()
root.geometry("500x900")
canvas = Canvas(root, width=550, height=820)
canvas.pack()
png = PhotoImage(file = r'example.png') # Just an example
canvas.create_image(0, 0, image = png, anchor = "nw")

a = canvas.create_rectangle(50, 0, 50, 0, fill='red')
canvas.move(a, 20, 20)

Hope this can be resolved.

2 Answers 2

40

The create_rectangle method takes 4 coordinates: canvas.create_rectangle(x1, y1, x2, y2, **kwargs), with (x1,y1) the coordinates of the top left corner and (x2, y2) those of the bottom right corner. But you gave twice the same coordinates so your rectangle has a zero width and height, that's why you can only see a pixel. Try with canvas.create_rectangle(50, 0, 100, 50, fill='red') and this time you should get a square of side 50 pixels.

You can get more details about the arguments of create_rectangle on this website.

Sign up to request clarification or add additional context in comments.

2 Comments

is (x2, y2) exclusive?
@Hzzkygcs What do you mean by that? Also, you can probably answer your own question by trying out the code.
6

Also, if you want to create a rectangle with dynamic size then you can do

canvas.create_rectangle(x, y, x+width, y+height, fill='red')

This will create a rectangle with your specified width and height.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.