【问题标题】:Adding an element on specific rows of a grid using Tkinter使用 Tkinter 在网格的特定行上添加元素
【发布时间】:2017-05-28 01:04:35
【问题描述】:

有没有办法使用 Tkinter 工具包在网格的特定行中添加按钮?

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

红色矩形是网格的元素(按钮)。 如您所见,与第一行相比,第二行多了一个按钮,以此类推。

所以,如果可能的话,我正在寻找一种方法来在我的网格中的特定行上显示一个额外的按钮。

代码如下:

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()

提前谢谢你。

【问题讨论】:

  • 那么到底是什么问题呢?这看起来像一个简单的 5x5 网格,在偶数行的奇数列中有水平按钮,在奇数行的偶数列中有垂直按钮。
  • 你的问题不清楚。我认为你需要改写它。运行您的代码的同时会输出一个 GUI,该 GUI 与“红色”图像突出显示的您想要实现的结果大不相同
  • 问题是我每行都有相同数量的按钮,但没有找到解决方法。但正如 jason 所说,我最终会显示一个 5x5 按钮的网格(白色的按钮不会做任何事情)。还是谢谢你
  • 您知道在使用grid 而不是pack 时可以指定准确的行和列吗?
  • 顺便说一下,Tk 有 GUI 构建器 ;)

标签: python if-statement tkinter


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多