[英]tkinter polygons
我對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)
,我在嘗試做一個正方形時沒有得到。
如圖所示,多邊形有兩個部分:其輪廓和內部。 它的幾何形狀指定為一系列頂點[[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)
。
這是有關create_polygon
函數的一些信息( 官方文檔 )。
根據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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.