Tkinter Canvas creating rectangle

时光怂恿深爱的人放手 提交于 2020-02-23 08:46:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/42039564/tkinter-canvas-creating-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!