tkinter多边形

问题描述 投票:2回答:2

我对tkinter比较新,我正在制作一个只使用正方形的游戏。我正在复制的那本书只显示三角形。这是代码:

# The tkinter launcher (Already complete)
from tkinter import *
HEIGHT = 500
WIDTH = 800
window = Tk()
window.title ('VOID')
c = Canvas (window, width=WIDTH, height=HEIGHT, bg='black')
c.pack()
# Block maker (Issue)
ship_id = c.create_polygon (5, 5, 5, 25, 30, 15, fill='red')

我没有得到任何错误,它只是一串数字,(5, 5, 5, 25, 30, 15),我没有得到,因为我正在努力建立一个正方形。

python python-3.x tkinter
2个回答
2
投票

Canvas.create_polygon definition的摘要:

如图所示,多边形有两个部分:轮廓和内部。它的几何被指定为一系列顶点[(x0,y0),(x1,y1),...(xn,yn)](...)

id = C.create_polygon(x0, y0, x1, y1, ..., option, ...)

所以你需要按照指定的顺序传递方块的坐标。例如:

myCanvas.create_polygon(5, 5, 5, 10, 10, 10, 10, 5)

可以读作

myCanvas.create_polygon(5,5, 5,10, 10,10, 10,5)

将创建一个顶点为(5, 5)(5, 10)(10, 10)(10, 5)的正方形。


1
投票

Here's关于create_polygon函数的一些信息(official docs)。

根据nmt.edu页面,函数调用的格式是

id = C.create_polygon(x0, y0, x1, y1, ..., option, ...)

这意味着ship_id = c.create_polygon (5, 5, 5, 25, 30, 15, fill='red')调用创建一个具有以下顶点的多边形:(5,5), (5,25), (30, 15)并用红色填充多边形。

如果要创建正方形,则必须执行以下操作:

ship_id = c.create_polygon (5, 5, 5,  25, 25, 25, 25, 5,  fill='red')

它创建了一个带顶点(5,5),(5,25),(25,25),(25,5)的矩形。

如果你想要一种更可重复的制造船舶的方法,你可以做类似的事情

def ship (x,y): 
    return [x-5, y-5, x+5, y-5, x+5, y+5, x-5, y+5]
ship_id = c.create_polygon(*ship(100, 500),  fill='red')

上面将创建一种船舶工厂(lambda函数),在其中您指定船舶中心的x和y,然后它给出了可用于create_polygon函数的顶点列表。

您甚至可以通过调整lambda函数来进一步指定船舶尺寸

def ship (x,y,w,h): 
    return [x-w/2, y-h/2, x+w/2, y-h/2, x+w/2, y+h/2, x-w/2, y+h/2]
ship_id = c.create_polygon(*ship(100, 500, 8, 8),  fill='red')
© www.soinside.com 2019 - 2024. All rights reserved.