tkinter:用图像制作 3x3 网格

tkinter: Making a 3x3 grid with an image

我有这些代码行:

def initialize_board(self):
    for i in range(2):
        self.canvas.create_line((i + 1) * size / 3, 0, (i + 1) * size / 3, size)

    for i in range(2):
        self.canvas.create_line(0, (i + 1) * size / 3, size, (i + 1) * size / 3)

这就是两条垂直线和两条水平线。 但我想用正方形图像的 3x3 网格替换它来表示相同的东西。我正在做一个井字游戏供参考。

这是我要使用的图片:

self.empty_image = PhotoImage(file = 'book/pybook/image/empty.gif')

谁能帮帮我?

如果您想制作井字游戏,最好创建一个 3x3 的按钮网格,然后在按钮上显示 X/O 的图像。

无论哪种方式,最好的办法是创建小部件,然后使用网格方法将其调用到 canvas。

Python grid() method in Tkinter

要在 Canvas 上显示图像,您需要为每个图像创建一个单独的 Canvas image object(除了 BitmapImagePhotoimage部件)。可以通过嵌套 for 循环轻松地将它们布置在网格中 — 一个循环迭代每一行,另一个循环迭代每一列。

注意从每个 Canvas.create_image() 调用返回的图像对象的整数 ID 号是如何存储在名为 self.board 的列表列表中的。以这种方式保存它们将允许关联的 Canvas 图像对象的 image 属性稍后在游戏进行时更改(通过 itemconfigure() Canvas 图形对象方法) .

下面是一个按照描述实现它的例子。

import tkinter as tk
WHITE = '#ffffff'

class Game:
    EMPTY_CELL_IMAGE_FILE_PATH = './ttt_empty.gif'

    def __init__(self, parent):
        self.empty_cell_image = tk.PhotoImage(file=self.EMPTY_CELL_IMAGE_FILE_PATH)
        self.width = 3 * self.empty_cell_image.width()
        self.height = 3 * self.empty_cell_image.height()
        self.canvas = tk.Canvas(parent, width=self.width, height=self.height,
                                background=WHITE)
        self.canvas.pack()
        self.initialize_board()

    def initialize_board(self):
        self.board = [[None for _ in range(3)] for _ in range(3)]  # Pre-allocate.
        width, height = self.empty_cell_image.width(), self.empty_cell_image.height()
        empty_cell_image = self.empty_cell_image
        for i in range(3):
            for j in range(3):
                self.board[i][j] = self.canvas.create_image(i*width, j*height,
                                                            anchor='nw',
                                                            image=empty_cell_image)

if __name__ == '__main__':
    root = tk.Tk()
    root.title('Tic-Tac-Toe')
    game = Game(root)
    root.mainloop()

结果: