python画布循环创建图像

2024-06-16 09:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我最近开始学习tkinter并决定学习棋盘游戏。
以下是我的代码:

import tkinter as tk

class GameBoard(tk.Frame):
    def __init__(self, parent, rows=8, columns=8, size=70, color1="white", color2="blue"):
        '''size is the size of a square, in pixels'''

        self.rows = rows
        self.columns = columns
        self.size = size
        self.color1 = color1
        self.color2 = color2
        self.pieces = {}

        canvas_width = columns * size
        canvas_height = rows * size

        tk.Frame.__init__(self, parent)
        self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0,
                                width=canvas_width, height=canvas_height, background="bisque")
        self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2)

root = tk.Tk()
board = GameBoard(root)
board.pack(side="top", fill="both", expand="true", padx=4, pady=4)

black_rook_l = tk.PhotoImage(file=black_rook_img)
black_rook_l = black_rook_l.subsample(2, 2)
board.addpiece("black_rook_l", black_rook_l, 0,0)

上面的代码i是向板中添加一个块(blackrook),它按预期工作。
下面是helper函数:

^{pr2}$

但当我试图在for循环的帮助下放置棋子时,问题就出现了。 代码如下:

for i in range(8):
    bname = tk.PhotoImage(file=black_pawn_img)
    bname = bname.subsample(2, 2)
    board.addpiece("black_pawn_"+str(i), bname, 1,i)

root.mainloop()

它只放置最后一块棋子。在

请建议/帮助我理解问题。
提前谢谢。在


Tags: columns代码selfboardsizewidthtkrows
1条回答
网友
1楼 · 发布于 2024-06-16 09:35:26

python图像对象正在被垃圾回收器销毁。您需要保存对图像的引用。第一次通过循环时,bname包含对创建的第一个映像的引用。在下一个迭代中,bname被修改为引用第二个图像。因此,第一个图像不再具有引用。在

一个简单的方法是在创建它们的代码块中跟踪它们:

images = []
for i in range(8):
    bname = tk.PhotoImage(file=black_pawn_img)
    bname = bname.subsample(2, 2)
    board.addpiece("black_pawn_"+str(i), bname, 1,i)
    images.append(bname)

另一种方法是让addpiece保存它们:

^{pr2}$

相关问题 更多 >