python - 将一堆代码变成循环Python

标签 python loops for-loop button tkinter

我想通过 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/

相关文章:

javascript - js变量只能在循环内访问

Python模块之间的依赖关系

python - 如何将 raw_input 重定向到 stderr 而不是 stdout?

python - 如何查看安装的 pip 包大小?

python - 确保角度小于 360 度的简单循环 [Python]

c - 不太奇怪的 C 行为

python - 在未聚焦的 Tkinter 文本小部件中突出显示单击的行

javascript - 将数组转换为字符串的函数循环,同时添加 <option>

java - 返回两个字符串不同的第一个位置

python - 如何使用循环抓取页面的所有项目