简体   繁体   English

Tkinter Canvas 创建矩形

[英]Tkinter Canvas creating rectangle

In python, tkinter, I'm trying to make a game that involves creating shapes onto a canvas.在 python 中,tkinter,我正在尝试制作一个涉及在画布上创建形状的游戏。 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.当我执行我的代码时,您看到的矩形大小约为 1 个像素,我不确定为什么以及如何变成那样。 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. create_rectangle方法需要 4 个坐标: canvas.create_rectangle(x1, y1, x2, y2, **kwargs) ,其中 (x1,y1) 左上角的坐标和 (x2, y2) 右下角的坐标。 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.尝试使用canvas.create_rectangle(50, 0, 100, 50, fill='red')这一次你应该得到一个边长为 50 像素的正方形。

You can get more details about the arguments of create_rectangle on this website .您可以在此网站上获得有关create_rectangle参数的更多详细信息。

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') 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 😅嗯,问这个问题已经 4 年零 3 个月了😅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM