如何清除 Tkinter 画布? [英] How to clear Tkinter Canvas?

查看:141
本文介绍了如何清除 Tkinter 画布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用以下方法绘制形状时:

When I draw a shape using:

canvas.create_rectangle(10, 10, 50, 50, color="green")

Tkinter 是否会跟踪它被创建的事实?

Does Tkinter keep track of the fact that it was created?

在我制作的一个简单游戏中,我的代码有一个 Frame 创建一堆矩形,然后绘制一个大的黑色矩形以清除屏幕,然后绘制另一组更新的矩形, 等等.

In a simple game I'm making, my code has one Frame create a bunch of rectangles, and then draw a big black rectangle to clear the screen, and then draw another set of updated rectangles, and so on.

我是否在内存中创建了数千个矩形对象?

Am I creating thousands of rectangle objects in memory?

我知道你可以将上面的代码分配给一个变量,但如果我不这样做而直接在画布上绘制,它会留在内存中,还是只绘制像素,就像在 HTML5 画布中一样?

I know you can assign the code above to a variable, but if I don't do that and just draw directly to the canvas, does it stay in memory, or does it just draw the pixels, like in the HTML5 canvas?

推荐答案

每个画布项都是 Tkinter 跟踪的对象.如果您只是通过绘制一个黑色矩形来清除屏幕,那么您实际上已经造成了内存泄漏——最终您的程序将因绘制了数百万个项目而崩溃.

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

要清除画布,请使用删除方法.给它一个特殊的参数 "all" 以删除画布上的所有项目(字符串 "all"" 是一个特殊的标签,代表画布上的所有项目):

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

如果您只想删除画布上的某些项目(例如前景对象,而将背景对象保留在显示器上),您可以为每个项目分配标签.然后,您可以提供标签的名称,而不是 "all".

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

如果您正在创建游戏,您可能不需要删除和重新创建项目.例如,如果您有一个在屏幕上移动的对象,您可以使用 movecoords 方法来移动项目.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

这篇关于如何清除 Tkinter 画布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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