简体   繁体   English

借助Python tkinter中的for循环绘制一个正方形

[英]Draw a square with the help of the for loop in Python tkinter

I want to draw 8 frames per side by using the for loop in Tkinter. 我想通过在Tkinter中使用for循环来绘制每边8帧。 First one white and then one black (like a chessboard). 第一个是白色,然后是一个黑色(如棋盘)。

from tkinter import *
window = Tk()
window.title("pyChess")
window.geometry("523x523+250+0")
window.configure( background = 'brown')

x1 = 0
y1 = 0
x2 = 65
y2 = 65
j1 = 65
k1 = 0
j2 = 130
k2 = 65

for i in range(8):
      i = Canvas(window, width=520, height=1000)
      i.create_rectangle(x1, y1, x2, y2, fill="white")
      x1 += 130
      x2 += 130
      i.create_rectangle(j1, k1, j2, k2, fill="black")
      j1 += 130
      j2 += 130

i.pack()
window.mainloop()

I wrote this code, but it didn't give me eight frames. 我写了这段代码,但它没有给我8帧。 It just opened a blank screen. 它只是打开一个空白屏幕。 What can I do for it? 我能做些什么?

You don't need to update the x1, x2, j1, j2 values for each Canvas widget. 您无需更新每个Canvas小部件的x1,x2,j1,j2值。 Either you draw all rectangles on the same Canvas (fow which the values of x1, x2, j1 and j2 need to be updated) or grid multiple Canvas widgets on each row. 要么在同一个画布上绘制所有矩形(需要更新x1,x2,j1和j2的值),要么在每行上绘制多个Canvas小部件。

Try the following code (rectangles are drawn only for the first row ): 尝试以下代码(仅为第一行绘制矩形):

from tkinter import *

window = Tk()    
window.title("pyChess")    
window.geometry("523x523+250+0")
window.configure( background = 'grey')

x1 = 0
y1 = 0
x2 = 65
y2 = 65
j1 = 65
k1 = 0
j2 = 130
k2 = 65
a = [0 , 1, 2, 3]

for x,i in enumerate(a):
    i = Canvas(window, width=130, height=65)
    i.create_rectangle(x1, y1, x2, y2, fill="white")
    i.create_rectangle(j1, k1, j2, k2, fill="black")
    i.grid(row = 0, column = x)

window.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM