2016-10-01 49 views
0

它又是我:) 我正在繼續我的遊戲項目。我被卡住了(作爲初學者): 我有一個表格(列表中有4個元素,每個元素的長度都很靈活,但這只是一個簡單的例子)。 所以這裏是我的代碼:如何根據表格(列表列表)在tkinter畫布上繪製正方形的表格?

from tkinter import* 
l=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] 
n=len(l) #this is the length of the list l 
lngt=400/len(l) #this is the dimension of the squares that I want 
fen=Tk() 
fen.geometry("600x400") 

#I would like to create a table of 4 rows on canvas 
#each row should contain 4 squares 
can=Canvas(fen,width=450,height=400,bg="lightblue") 
can.pack(side=LEFT) 
for i in range(n): 
    can.create_rectangle(n, i*(lngt) ,n+lngt, i*n+(i+1)*lngt,  fill="red") 

f=Frame(fen,width=150,height=400,bg="lightcoral") 
f.pack(side=LEFT) 

fen.mainloop() 

截至目前,我只在畫布的左側獲得的4個方格列。我所有的試驗都未能創造另外12個方格。

謝謝真棒的人!

+1

嘗試在'for'循環中設置'for'循環。外部循環可以用於列,而內部循環用於其中一列中的每一行。 – jcfollower

+1

你是什麼意思「12個其他廣場」?那'l'的長度是4,所以'n'是4.'l'的目的是什麼?除了計算長度,您發佈的代碼並不使用它。 –

+0

我試過了,但沒有太大變化。我嘗試了一個「j」,但我真的不知道在哪裏使用「j」。 – Chihab

回答

1

以下是如何在畫布上繪製正方形方格。

import tkinter as tk 

l = [[0,0,0,0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 
n = len(l)  #this is the length of the list l 
lngt = 400 // n #this is the dimension of the squares that I want 

fen = tk.Tk() 
fen.geometry("600x400") 

#I would like to create a table of 4 rows on canvas 
#each row should contain 4 squares 
can = tk.Canvas(fen, width=450, height=400, bg="lightblue") 
can.pack(side=tk.LEFT) 

for i in range(n): 
    y = i * lngt 
    for j in range(n): 
     x = j * lngt 
     can.create_rectangle(x, y, x+lngt, y+lngt, fill="red") 

f = tk.Frame(fen, width=150, height=400, bg="lightcoral") 
f.pack(side=tk.LEFT) 

fen.mainloop() 
相關問題