Tkinter网格内按钮的居中位置

时间:2019-04-11 18:04:58

标签: python user-interface tkinter

我正在尝试为我的项目编写四连体游戏。我使用tkinter时没有任何经验。我使用的是grid()布局,包含3行(标题显示为第一行,按钮显示为第二行,画布显示游戏显示为第三行)和6列。 我遇到的问题是使按钮出现在每一列的顶部。甚至第一个按钮也不在第一列的中间,并且每个下一个按钮的位置越来越多。我认为这些列的宽度应相同,因为它们都完全具有相同的按钮。

P1是我的课程,拥有我打算更改的实际游戏板和行/列的数量。

我尝试过使用grid_rowconfigure这样的方法:

self.grid_rowconfigure(1, weight=1)

但这似乎没有效果。

#Main.py
class Game:
    def __init__(self, roows, coolumns):
        self.rows = roows
        self.columns = coolumns
        self.gameTable = [["x" for x in range(self.columns)] for y in range(self.rows)]
        self.which_row = [5 for x in range(self.columns)]
from tkinter import *
import Main

class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master

        self.master.title("connect four")
        self.grid()

        Tytul = Label(self, text="Hello", font=("Helvetica", 24), fg="medium blue")
        Tytul.grid(row=0, columnspan=6)

        for i in range(P1.columns):
            button = Button(self, text="▼")
            button.grid(row=1, column=i)
        #self.grid_rowconfigure(1, weight=1)

    def draw_gametable(self):
        canvas1 = Canvas(self, relief=FLAT, background="#D2D2D2",
                         width=P1.columns*100, height=P1.rows*100)
        canvas1.grid(row=2, columnspan=6)

        cellwidth = 100
        cellheight = 100

        for column in range(P1.columns):
            for row in range(P1.rows):
                if P1.gameTable[row][column] == "x":
                    color = "grey"
                elif P1.gameTable[row][column] == "z":
                    color = "yellow"
                elif P1.gameTable[row][column] == "c":
                    color = "Red"
                x1 = column * cellwidth
                y1 = row * cellheight
                x2 = x1 + cellwidth
                y2 = y1 + cellheight
                canvas1.create_rectangle(x1, y1, x2, y2, fill="cornflower blue")
                canvas1.create_oval(x1 + 2, y1 + 2, x2 - 2, y2 - 2, fill=color,  
                                    tags="oval")

if __name__ == "__main__":
    P1 = Main.Game(6, 7)
    root = Tk()
    instance = Window(root)
    instance.draw_gametable()
    root.mainloop()

This is how i would like it to look

1 个答案:

答案 0 :(得分:0)

您有7列,但使画布跨度只有6列。 resource.latestData的意思不是“要跨越多少更多列”,而是“要跨越多少总共 列”。

如果让画布跨越所有7列,则所有内容都会对齐:

columnspan
相关问题