Python 使用Tkinter在网格的特定行上添加元素

Python 使用Tkinter在网格的特定行上添加元素,python,if-statement,tkinter,Python,If Statement,Tkinter,有没有一种方法可以使用Tkinter toolkit在网格的specifics行中添加按钮 我目前正在尝试这样的网格设置: 其中,红色矩形是网格元素(按钮)。 如您所见,与第一行相比,第二行有一个额外的按钮,依此类推 因此,如果可能的话,我正在寻找一种方法来显示一个额外的按钮来指定我的网格中的行 代码如下: import sys import tkinter as tk from tkinter import * fenetre = Tk() #frame 1 Frame1 = Fra

有没有一种方法可以使用Tkinter toolkit在网格的specifics行中添加按钮

我目前正在尝试这样的网格设置:

其中,红色矩形是网格元素(按钮)。 如您所见,与第一行相比,第二行有一个额外的按钮,依此类推

因此,如果可能的话,我正在寻找一种方法来显示一个额外的按钮来指定我的网格中的行

代码如下:

import sys
import tkinter as tk
from tkinter import * 


fenetre = Tk()

#frame 1
Frame1 = Frame(fenetre, borderwidth=2, relief=GROOVE)
Frame1.pack(fill=BOTH)

#frame2
Frame2 = Frame(fenetre, borderwidth=2, relief=GROOVE)
Frame2.pack(fill=BOTH)

#grid display
def afficheGrille():

    tailleGrille=(int(s.get()))

    for ligne in range((tailleGrille * 2) +1):
        for colonne in range(tailleGrille):
            if(ligne == 0 or (ligne % 2) == 0):
                #boutons horizontaux
                Button(Frame2, borderwidth=1, height=1, width=8).grid(row=ligne, column=colonne)
            else:
                #boutons verticaux
                Button(Frame2, borderwidth=1, height=5, width=2).grid(row=ligne, column=colonne)



label = Label(Frame1, text="Jeu du carré")
label.pack()

boutonJvIA=Button(Frame1, text="1 joueur vs IA", width=30, command=afficheGrille)
boutonJvIA.pack()

boutonJvJ=Button(Frame1, text="1 joueur vs 1 joueur", width=30, command=afficheGrille)
boutonJvJ.pack()

s = Spinbox(Frame1, from_= 0, to = 100)
s.pack()



fenetre.mainloop()

提前感谢。

通过调整for循环中的索引,并在
.grid()
方法中指定正确的
参数,您将获得所需的对齐方式:

for ligne in range( tailleGrille*2 + 1):
    if (ligne % 2) == 0:
        #boutons horizontaux
        for colonne in range(tailleGrille):
            Button(Frame2, bd=1, height=1, width=8).grid(row=ligne, column=2*colonne+1)
    else:
        #boutons verticaux
        for colonne in range(tailleGrille + 1):
            Button(Frame2, bd=1, height=5, width=2).grid(row=ligne, column=2*colonne)

通过调整for循环中的索引,并在
.grid()
方法中指定正确的
参数,您将获得所需的对齐方式:

for ligne in range( tailleGrille*2 + 1):
    if (ligne % 2) == 0:
        #boutons horizontaux
        for colonne in range(tailleGrille):
            Button(Frame2, bd=1, height=1, width=8).grid(row=ligne, column=2*colonne+1)
    else:
        #boutons verticaux
        for colonne in range(tailleGrille + 1):
            Button(Frame2, bd=1, height=5, width=2).grid(row=ligne, column=2*colonne)

那么到底是什么问题呢?这看起来像一个简单的5x5网格,在偶数行的奇数列中有水平按钮,在奇数行的偶数列中有垂直按钮。你的问题不清楚。我想你需要重新措辞。运行您的代码时,也会输出一个GUI,它与“红色”图像所突出显示的图形非常不同。问题是,我在每一行上都有相同数量的按钮,但没有找到解决方法。但正如jason所说,我最终将显示一个由5x5个按钮组成的网格(白色按钮不会做任何事情)。谢谢你,你知道你可以在使用
grid
而不是
pack
时指定确切的行和列吗?顺便说一下,Tk有GUI生成器;)那么到底是什么问题呢?这看起来像一个简单的5x5网格,在偶数行的奇数列中有水平按钮,在奇数行的偶数列中有垂直按钮。你的问题不清楚。我想你需要重新措辞。运行您的代码时,也会输出一个GUI,它与“红色”图像所突出显示的图形非常不同。问题是,我在每一行上都有相同数量的按钮,但没有找到解决方法。但正如jason所说,我最终将显示一个由5x5个按钮组成的网格(白色按钮不会做任何事情)。谢谢你,你知道你可以在使用
grid
而不是
pack
时指定确切的行和列吗?顺便说一下,Tk有GUI生成器;)