Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Canvas creating rectangle

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.

like image 476
Jake Avatar asked Feb 04 '17 11:02

Jake


2 Answers

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.

like image 140
j_4321 Avatar answered Oct 31 '22 04:10

j_4321


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.

like image 4
Parth jadhav Avatar answered Oct 31 '22 03:10

Parth jadhav