我想通过 python tkinter 使用按钮绘制井字游戏板。但我发现我的代码效率很低。谁能帮我将代码转换为循环吗?
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()
最佳答案
也许这可以帮助你
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()
关于python - 将一堆代码变成循环Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57428907/