首页 > 解决方案 > Tkinter 函数“root.after()”不运行指定的函数

问题描述

当我使用 Tkinter 函数“root.after()”时,它只运行一次指定的函数。在我的情况下,这是“移动”功能,在我的代码底部的第二行中。总的来说,我正在尝试对椭圆做一个基本的动画。

我正在运行 Python 3.7.1。

from tkinter import *

class shape:
    def __init__(self, canvas):
        self.canvas = canvas
        self.EdgeThickness = 1
        self.color="#ffffff"


    def animation(self,xposgiven):        
        self.shape = self.canvas.create_oval(xposgiven,250,250,400,fill=self.color,width=self.EdgeThickness)
        print('runninganimation')


root=Tk() 
c=Canvas(root, width=1000, height=500)
c.pack()
c.configure(background="#000000")

s=shape(c)
s.xpos=5

def move():
    print('runningmove')
    s.xpos+=5
    s.animation(s.xpos)

root.after(100,move)
root.mainloop()  

我预计函数 move() 将每 100 毫秒运行一次,但它只运行一次。我认为函数 root.after(time,func) 每隔 'time' ms 运行一次函数 'func'。但在我的代码中似乎没有这样做。它只运行一次。

标签: pythonpython-3.xtkinter

解决方案


after安排一个作业只运行一次。如果您希望它每 100 毫秒运行一次,一个常见的策略是让您的函数调用after在返回之前将其自身作为参数。

> import tkinter
> help(tkinter.Tk.after)
after(self, ms, func=None, *args)
    Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel.

推荐阅读