用tkinter创建钻石

时间:2017-06-01 14:50:45

标签: python tkinter

如果我运行以下代码:

from tkinter import *
window = Tk()
window.geometry( "500x500+100+100" ) 
window.attributes( "-topmost", True ) 
c = Canvas( window, width=500, height=500 )

d = 0
while d < 7:
    a = 7-d
    while a <7:
        c.create_rectangle( a * 40, d * 40, a * 40+37, d * 40+37, fill="blue", outline="" )
        a += 1
    d += 1

d = 0
while d < 7:
    a = 0
    while a <d:
        c.create_rectangle( a * 40+240, d * 40, a * 40+240+37, d * 40+37, fill="blue", outline="" )
        a += 1
    d += 1

c.pack()
mainloop()

它只显示钻石的上半部分:

enter image description here

我也想创建下半部分。我该怎么做?

2 个答案:

答案 0 :(得分:1)

好吧,通过否定y翻转三角形:

d = 0
while d < 7:
    a = 7-d
    while a <7:
        c.create_rectangle( a * 40, -(d * 40), a * 40+37, -(d * 40+37), fill="blue", outline="" )

        a += 1
    d += 1


d = 0
while d < 7:
    a = 0
    while a <d:
        c.create_rectangle( a * 40+240, -(d * 40), a * 40+240+37, -(d * 40+37), fill="blue", outline="" )

        a += 1
    d += 1

这当然会将你的三角形放在画布的顶部上方,所以接下来你需要将它向下移动直到它到达中间,这是到现在中间距离的两倍(240*2+37):< / p>

d = 0
while d < 7:
    a = 7-d
    while a <7:
        c.create_rectangle( a * 40, 240*2+37-(d * 40), a * 40+37, 240*2+37-(d * 40+37), fill="blue", outline="" )

        a += 1
    d += 1


d = 0
while d < 7:
    a = 0
    while a <d:
        c.create_rectangle( a * 40+240, 240*2+37-(d * 40), a * 40+240+37, 240*2+37-(d * 40+37), fill="blue", outline="" )

        a += 1
    d += 1

将其添加到代码的底部,您就可以获得钻石了。

答案 1 :(得分:0)

我喜欢你是怎么做到的,但我认为制作你想要的ASCII'地图'然后将其转换为tkinter会更简单。使用此方法,您可以轻松扩大尺寸。

from tkinter import *
window = Tk()
window.geometry( "500x500+100+100" ) 
window.attributes( "-topmost", True ) 
c = Canvas( window, width=500, height=500 )

inputNumber = 11+2
grid = [" "*int((inputNumber-i)/2)+"X"*i for i in range(1,inputNumber,2)]
grid += grid[::-1][1:]
for y, row in enumerate(grid):
    for x, item in enumerate(row):
        if item == "X":
            c.create_rectangle( x * 40, y * 40, x * 40+37, y * 40+37, fill="blue", outline="" )

c.pack()
mainloop()