Tkinter画布创建矩形 [英] Tkinter Canvas creating rectangle
问题描述
在python中,我尝试创建一个涉及在画布上创建形状的游戏。例如,我希望在我的画布图像上出现一个红色矩形。当我执行代码时,您看到的矩形的大小约为1像素,但我不确定为什么以及这样的矩形。这是我的代码:
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)
希望这可以解决。 / p>
Hope this can be resolved.
推荐答案
create_rectangle
方法采用4个坐标:
canvas.create_rectangle(x1,y1,x2,y2,** kwargs)
,其中(x1,y1)的坐标为左上角,(x2,y2)的坐标为右下角。但是您给了两次相同的坐标,因此矩形的宽度和高度为零,这就是为什么只能看到一个像素的原因。尝试使用 canvas.create_rectangle(50,0,100,50,fill ='red')
,这一次您应该获得侧面50像素的正方形。
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.
这篇关于Tkinter画布创建矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!