I wrote cellular automaton (Conway's Game of Life) using Perl and TK, just for fun and practice. It works fine with console output. When I use TK, in first version I just delete and add new cells (rectangles), and after about 100 steps my program has slowed down (about 10 times). Then I rewrote graphics part: initially made all of 2500 cells (50x50) and then changing their color instead of adding/deleting them. But after 600-700 steps my reworked automaton begins to slow down too.
我使用Perl和TK编写元胞自动机(Conway's Game of Life),只是为了好玩和练习。它在控制台输出中工作得很好。当我使用TK时,在第一个版本中,我只是删除并添加新的单元格(矩形),在大约100步之后,我的程序就变慢了(大约10次)。然后我重写了图形部分:最初制作了2500个单元(50x50),然后改变它们的颜色,而不是添加或删除它们。但经过600-700步后,我重新设计的自动机器人也开始慢下来。
This is a feature/bug of TK or I do something wrong?
这是TK的一个特性/bug,还是我做错了什么?
Changing color by tag:
改变颜色的标签:
$canvas->itemconfigure("cell"."$x $y", -fill=>'blue');
Creating grid:
创建网格:
for($y = 0; $y < 50; $y++)
{
for($x = 0; $x < 50; $x++)
{
$canvas->createRectangle($x * 10, $y * 10, ($x + 1) * 10, ($y + 1) * 10, -fill=>'white', -tags=>["cell"."$x $y"]);
}
}
Start and stop loop:
启动和停止循环:
sub start
{
$repeat = $MainWindow->repeat($speed, sub{&maketurn;});
# Function "maketurn" is not important, it is a simple counting of "alive" cells
# and changing color by tag
}
sub stop
{
if(defined($repeat))
{
$repeat->cancel();
}
}
1 个解决方案
#1
1
I found an articles about the tk canvas widget being slow with many items. The problem sounds very similar to your problem:
我发现有一篇关于tk canvas小部件在很多项目上运行缓慢的文章。这个问题听起来很像你的问题:
http://code.activestate.com/lists/perl-tk/17282/
http://code.activestate.com/lists/perl-tk/17282/
The solution may be to use the tk photo widget which behaves much like a bitmap. This would be a little of a pain to adapt your code to but it seems like the canvas widget is inherently slow with many objects.
解决方案可能是使用tk photo小部件,它的行为非常类似位图。调整代码以适应这种情况会有点麻烦,但是看起来canvas小部件在处理许多对象时天生就很慢。
#1
1
I found an articles about the tk canvas widget being slow with many items. The problem sounds very similar to your problem:
我发现有一篇关于tk canvas小部件在很多项目上运行缓慢的文章。这个问题听起来很像你的问题:
http://code.activestate.com/lists/perl-tk/17282/
http://code.activestate.com/lists/perl-tk/17282/
The solution may be to use the tk photo widget which behaves much like a bitmap. This would be a little of a pain to adapt your code to but it seems like the canvas widget is inherently slow with many objects.
解决方案可能是使用tk photo小部件,它的行为非常类似位图。调整代码以适应这种情况会有点麻烦,但是看起来canvas小部件在处理许多对象时天生就很慢。