无法将带有网格的按钮添加到tkin中的列表中

2024-04-25 19:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用tkinter来安排这样的按钮: Screenshot

这适用于以下代码:

from tkinter import *

root = Tk()
root.title("Tic Tac Toe")

btn = []

def btnClicked (btnNum):
    print(btnNum)

b=0
for a in range(9):
    if(a%3 == False):
        b = b+1
    btn.append(Button(root, text="", command = lambda c=a: btnClicked(c), height = 10, width = 20).grid(row = a-3*(b-1), column=b))

root.mainloop()

但是,为了对这些按钮执行操作,我需要将它们打包,如下所示:

from tkinter import *

root = Tk()
root.title("Tic Tac Toe")

btn = []

def btnClicked (btnNum):
    print(btnNum)
    btn[btnNum]["text"] = "X"

b=0
for a in range(9):
    if(a%3 == False):
        b = b+1
    btn.append(Button(root, text="", command = lambda c=a: btnClicked(c), height = 10, width = 20).grid(row = a-3*(b-1), column=b))
    btn[a].pack()

root.mainloop()

运行此代码时出现以下错误:

AttributeError: 'NoneType' object has no attribute 'pack'

当我不在网格中排列按钮时,如我所愿,此代码可以工作:

from tkinter import *

root = Tk()
root.title("Tic Tac Toe")

btn = []

def btnClicked (btnNum):
    print(btnNum)
    btn[btnNum]["text"] = "X"

b=0
for a in range(9):
    if(a%3 == False):
        b = b+1
    btn.append(Button(root, text="", command = lambda c=a: btnClicked(c), height = 10, width = 20))
    btn[a].pack()

root.mainloop()

如何在第二个代码示例中消除错误,或者在第三个示例中分别对齐网格中的按钮?你知道吗


Tags: 代码textfromimporttitletkinterroottic
1条回答
网友
1楼 · 发布于 2024-04-25 19:41:50

下面是代码的问题及其解决方案。你知道吗

  1. 您不需要使用两个变量ab。只需使用一个模数(a//3)和余数(a%3)即可。

  2. 如果你打印出btn列表,你会马上意识到这个问题。它由None组成,只是因为您在对按钮执行grid操作后追加了,该操作返回None。您需要首先附加小部件,然后将其“网格化”。

所以,这里是工作代码。你知道吗

from tkinter import *

root = Tk()
root.title("Tic Tac Toe")

btn = []

def btnClicked(btnNum):
    print(btnNum)
    btn[btnNum]["text"] = "X"

for a in range(9):
    btn.append(Button(root, text="", command = lambda c=a: btnClicked(c), height = 10, width = 20))
    btn[-1].grid(row = a%3, column=a//3)

root.mainloop()

enter image description here

相关问题 更多 >