将一堆代码变成循环Python

时间:2019-08-09 11:15:20

标签: python loops for-loop button tkinter

我想通过python tkinter使用按钮绘制tictactoe板。但是我发现我的代码效率低下。谁能帮我将代码转换成循环吗?

import tkinter as tk
main = tk.Tk()

box1 = tk.Button(main, textvariable = box_text1, width=15, height=5)
box1.grid(row=0, column=0)
box2 = tk.Button(main, textvariable = box_text2, width=15, height=5)
box2.grid(row=0, column=1)
box3 = tk.Button(main, textvariable = box_text3, width=15, height=5)
box3.grid(row=0, column=2)
box4 = tk.Button(main, textvariable = box_text4, width=15, height=5)
box4.grid(row=1, column=0)
box5 = tk.Button(main, textvariable = box_text5, width=15, height=5)
box5.grid(row=1, column=1)
box6 = tk.Button(main, textvariable = box_text6, width=15, height=5)
box6.grid(row=1, column=2)
box7 = tk.Button(main, textvariable = box_text7, width=15, height=5)
box7.grid(row=2, column=0)
box8 = tk.Button(main, textvariable = box_text8, width=15, height=5)
box8.grid(row=2, column=1)
box9 = tk.Button(main, textvariable = box_text9, width=15, height=5)
box9.grid(row=2, column=2)

main.mainloop()

2 个答案:

答案 0 :(得分:1)

也许这可以帮助您

import tkinter as tk
main = tk.Tk()

boxes_list = []
for i in range(3):
        for j in range(3):
                box = tk.Button(main, textvariable = "box_text" + str(i*3 + j + 1), width=15, height=5)
                box.grid(row=i, column=j)
                boxes_list.append(box)
main.mainloop()

答案 1 :(得分:0)

您将需要一些新东西:

  • 用于计算框坐标的代码
  • 两个列表,用于存储所有框和文本变量

坐标计算

row = num_box // 3
col = num_box % 3

列表

boxes = []
vars = []

其余的很简单:

for num_box in range(9):
    row = num_box // 3
    col = num_box % 3
    textvar = tk.StringVar()
    box = tk.Button(main, textvariable = textvar, width=15, height=5)
    box.grid(row=row, column=col)
    boxes.append(box)
    vars.append(textvar)