有没有办法将画布小部件在窗口中居中?

时间:2019-06-20 04:58:42

标签: python python-3.x tkinter tkinter-canvas

我正在使用Tkinker / Python构建国际象棋程序。我正在尝试将板子对准窗口的中心,以便将所取的碎片放在板子旁边。有什么想法吗?

from tkinter import *
root=Tk()

class Board():  
    def drawboard():


        dark="#643c22"
        light="#faeac6"

        canvas=Canvas(root, width=920, height=720,)
        canvas.pack( fill=BOTH)
        colour=light
        for row in range(8):
            if colour==dark:
                colour=light
            else:
               colour=dark 
            for column in range(8):
                x1 = (column * 90)
                y1 = ((7-row)* 90)
                x2 = x1 + 90
                y2 = y1 + 90
                canvas.create_rectangle(x1, y1, x2, y2, fill=colour)

                if colour==dark:
                    colour=light
                else:
                    colour=dark


Board.drawboard()


root.mainloop()

我希望它在中心对齐,但它向左对齐。

1 个答案:

答案 0 :(得分:0)

您创建的类只是一些函数的容器...您可能需要阅读一些有关面向对象的python的知识,并熟悉其具体内容。我改写了您的课程Board作为示例;它继承自tk.Tk,因此是tkinter root

就各种小部件的放置而言,我添加了一个左右框架,以使代表棋盘格的画布居中。

它是这样的:

import tkinter as tk


class Board(tk.Tk):

    colours = ["#643c22", "#faeac6"]

    def __init__(self, n=8):
        super().__init__()
        self.n = n
        self.left_frame = tk.Frame(self)
        self.left_frame.grid(row=0, column=0, rowspan=8, padx=100)
        self.right_frame = tk.Frame(self)
        self.right_frame.grid(row=0, column=10, rowspan=8)
        self.canvas = tk.Canvas(self, width=920, height=720, )
        self.canvas.grid(row=0, column=1, columnspan=8, rowspan=8)
        self.board = [[None for row in range(n)] for col in range(n)]
        self.current_colour_ndx = 0

    def _swap_colours(self):
        self.current_colour_ndx = (self.current_colour_ndx + 1) % 2

    def drawboard(self):

        for col in range(self.n):
            self._swap_colours()
            for row in range(self.n):
                x1 = col * 90
                y1 = (7-row) * 90
                x2 = x1 + 90
                y2 = y1 + 90
                colour = self.colours[self.current_colour_ndx]
                self.board[row][col] = self.canvas.create_rectangle(x1, y1, x2, y2, fill=colour)
                self._swap_colours()


if __name__ == '__main__':

    board = Board()
    board.drawboard()
    board.mainloop()

enter image description here