在循环中使用tkinter图片画布? [英] Using a tkinter image canvas in a loop?

查看:74
本文介绍了在循环中使用tkinter图片画布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始研究 tkinter ,并决定选择这个突破性游戏并对其进行研究/修改。

I recently started studying tkinter and decided to pick up this block breaker game and study/modify it.

因此,该问题发生在以下几行:

So the problem occur in the following lines:

blocks = []
block.xLoc = 50
block.yLoc = 50
block.xsize = 40
block.ysize = 30
for x in range(4):
    for y in range(20):
        blockC = PhotoImage(file = "block.png")
        blockID = canvas.create_image(block.xLoc,block.yLoc,image=blockC)
        canvas.grid()
        blocks.append(blockID)
        block.xLoc += 40
    block.yLoc += 30
    block.xLoc = 50

我想拥有多个图像块,但它只给了我一个图像块
&其他块不可见,但仍能正常工作(球反弹)。

I want to have multiple image blocks but instead its only give me a single block & other blocks are not visible but still functional (Ball bounces back).

我该如何解决?

这是用于比较的原始代码:
(此代码工作正常,但使用矩形画布。)

This is the original code for comparison: (This one is working perfectly but its using a rectangle canvas.)

blocks = []
block.xLoc = 50
block.yLoc = 50
block.xsize = 40
block.ysize = 30
for x in range(4):
    for y in range(20):
        blockID = canvas.create_rectangle([block.xLoc, block.yLoc,
                                           block.xLoc+block.xsize,
                                           block.yLoc+block.ysize],
                                          fill="white")
        canvas.grid()
        blocks.append(blockID)
        block.xLoc += 40
    block.yLoc += 30
    block.xLoc = 50


推荐答案

正如@Bryan Oakley指出的那样,您需要保留对 PhotoImage 对象的引用在循环中的某个地方进行操作,这样,只要将新值放入最内部循环中使用的临时 blockC 临时变量中,它们就不会被垃圾回收。

As @Bryan Oakley pointed out, you need to keep references to the PhotoImage objects created in the loop somewhere so they aren't garbage collected as soon as you put a new value in the temporary blockC variable used inside the innermost loop.

从问题中的代码片段很难确定,但是类似以下的内容应该可以解决问题。由于所有块的图片都是相同的,因此没有理由在内循环本身中加载80个副本。进入循环之前,只需加载一次并反复使用即可。

It's difficult to tell for sure from the fragment of code in your question, but something like the following should fix the problem. Since the image for all the blocks is the same, there's no reason to load 80 copies of it in the inner loop itself. Just load it once before entering the loop and use it over-and-over.

blocks = []
block.xLoc = 50
block.yLoc = 50
block.xsize = 40
block.ysize = 30
blockC = PhotoImage(file="block.png")  # moved outside loop
for x in range(4):
    for y in range(20):

        blockID = canvas.create_image(block.xLoc, block.yLoc, image=blockC)

        canvas.grid()
        blocks.append(blockID)
        block.xLoc += 40
    block.yLoc += 30
    block.xLoc = 50

这篇关于在循环中使用tkinter图片画布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆