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.
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 .
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.
Well it's been 4 yrs and 3 months after asking this question 😅
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.