Rod*_*ele 0 python tkinter python-2.7 pillow
我正在尝试使用after_cancel来停止简单图像查看器中的动画循环.我已经阅读了关于Tcl的文档,在这里搜索并google,并探索了python subreddits.我的错误是:
TclError: wrong # args: should be "after cancel id|command"
Run Code Online (Sandbox Code Playgroud)
这发生在以下代码的最后一行(请不要因为使用全局变量而杀了我,这个项目只是一个图像查看器来显示我们办公室的天气预报产品):
n_images = 2
images = [PhotoImage(file="filename"+str(i)+".gif") for i in range(n_images)]
current_image = -1
def change_image():
displayFrame.delete('Animate')
displayFrame.create_image(0,0, anchor=NW,
image=images[current_image], tag='Animate')
displayFrame.update_idletasks() #Force redraw
callback = None
def animate():
forward()
callback = root.after(1000, animate)
def forward():
global current_image
current_image += 1
if current_image >= n_images:
current_image = 0
change_image()
def back():
global current_image
current_image -= 1
if current_image < 0:
current_image = n_images-1
change_image()
def stop():
root.after_cancel(callback)
Run Code Online (Sandbox Code Playgroud)
如果有更合适的方法来停止Tkinter中的动画循环,请告诉我!
使用的另一种方法after_cancel
是,您可以使用额外的全局值来跟踪循环是否应该继续.
should_continue_animating = True
def animate():
forward()
if should_continue_animating:
root.after(1000, animate)
def stop():
global should_continue_animating
should_continue_animating = False
Run Code Online (Sandbox Code Playgroud)
额外设计提示:将所有功能都放入单个类的方法中可能很有用.那么你将拥有self.current_image
而self.should_continue_animating
不是全局值.如果您想一次动画多个图像,这将是一个很好的设计选择.
您这里的代码不是设置全局变量,而是设置局部变量:
callback = None
def animate():
forward()
callback = root.after(1000, animate)
Run Code Online (Sandbox Code Playgroud)
在这里,callback
将保持设置为None
,因此您root.after_cancel(callback)
的等效于root.after_cancel(None)
TK 不喜欢的 。尝试将您的animate
功能更改为:
def animate():
global callback
forward()
callback = root.after(1000, animate)
Run Code Online (Sandbox Code Playgroud)
免责声明:我同意 Kevin 的观点,全局变量会迅速繁殖并开启它们的主控,因此请使用类。然后变量被锁定,无法得到你。
归档时间: |
|
查看次数: |
2727 次 |
最近记录: |