Python Tkinter Canvas 创建矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42039564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tkinter Canvas creating rectangle
提问by Jake
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:
在 python 中,tkinter,我正在尝试制作一个涉及在画布上创建形状的游戏。例如,我想要一个红色矩形出现在我的画布图像上。当我执行我的代码时,您看到的矩形大小约为 1 个像素,我不确定为什么以及如何变成那样。这是我的代码:
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.
希望这能得到解决。
回答by j_4321
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.
该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 像素的正方形。
You can get more details about the arguments of create_rectangle
on this website.
您可以create_rectangle
在此网站上获得有关 的更多详细信息。