这是一个生命游戏应用程序,并使用 after 来减缓细胞在出生、生命、死亡等阶段的动画。之后的几个问题:1.我一直在广泛研究 Tkinter 并且这篇文章捕获了我发现的最清晰的关于 after 参数的说明,但是,我的 Tkinter 应用程序不起作用 - 根据已经收到的评论,它可能不是之后,但这就是症状所在出现?2.当我不把参数放在后面的括号里时,基本上后面似乎根本不起作用(例如 widget.after(200, self.my_function, parameter 1, parameter 2, ....) 't 迭代。但是,当我执行相同操作但包含它按预期迭代的参数时(例如,widget.after(200, self.my_function(parameter 1, parameter 2, ....))。3.然而,当用括号中的参数运行时,后挂起。下面代码中的列表包含 81 个项目,并非巧合的是,该函数挂起 16.2 秒...代码如下: def color_cells( self, cells, repeater, temp_cells=0, counter=0, after_id=None ): global paused if temp_cells != 0: self.repeat_colors(temp_cells) temp_cells.clear() temp_cells = 0 for key in cells: if cells[key][0] == 'emerging': cells[key] = 'active', colors['active'][1] if cells[key][0] == 'dying': cells[key] = 'inactive', colors['inactive'][1] counter = 0 if repeater and not paused: print("repeater is ", repeater, " and paused is ",paused) self.id_changes(cells) else: self.closeoutGame()布莱恩,你曾要求提供错误示例。为了显示错误,我向调用函数添加了一些打印语句,然后解释了 16.2 秒不活动时间段的开始位置: starting repeat colors and the temps cells len is 81 and the counter is 0 starting repeat colors and the temps cells len is 81 and the counter is 1 starting repeat colors and the temps cells len is 81 and the counter is 2 ... starting repeat colors and the temps cells len is 81 and the counter is 79 starting repeat colors and the temps cells len is 81 and the counter is 80 starting repeat colors and the temps cells len is 81 and the counter is 81 ...hangs for the 16.2 seconds, equal to 200 ms x 81 iterations我是一个业余爱好者,没有接受过正规培训,所以我确信我在这里忽略了一些基本的东西,包括如何最好地自己研究。但我感谢任何建议。
4 回答

UYOU
TA贡献1878条经验 获得超4个赞
你的问题是由root.after(200, self.repeat_colors(temp_cells, counter))
. 相反,您需要将您的self.repeat_colors
作为 lambda传递。
所以发生的事情是self.repeat_colors(temp_cells, counter)
立即调用而不是等待 200 秒。因此,而是创建一个 lambda 函数,该函数将等到设定的时间激活。
请记住 lambda 表达式,如果您有一个更改的值,您需要在 lambda 中定义它。所以对于计数器,你需要做一些类似x=counter
的事情,所以 lambda 肯定会使用正确的更新值。这通常会影响诸如创建 lambda 表达式的循环之类的东西,在这种特殊情况下可能无关紧要,但在重要时练习是一个好习惯。
改变这个:
root.after(200, self.repeat_colors(temp_cells, counter))
对此:
root.after(200, lambda x=counter: self.repeat_colors(temp_cells, x))
添加回答
举报
0/150
提交
取消