Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 努力在Tkinter中设置图像动画_Python_Tkinter - Fatal编程技术网

Python 努力在Tkinter中设置图像动画

Python 努力在Tkinter中设置图像动画,python,tkinter,Python,Tkinter,我已经开始编写一个Connect 4游戏(点击会触发光盘掉落),我想制作光盘掉落的动画。 因此,我首先创建一个新的光盘映像: discList[y][x] = can.create_image((xCan,yCurrent), image=imgRedDisc, anchor="nw") 光盘是在xCan的画布顶部创建的;电流。我现在要做的是制作光盘掉落到其目的地yCan的动画。我调用我的drop函数,该函数不断增加光盘的yCurrent,直到它通过递归和after()方法到达yCan: de

我已经开始编写一个Connect 4游戏(点击会触发光盘掉落),我想制作光盘掉落的动画。 因此,我首先创建一个新的光盘映像:

discList[y][x] = can.create_image((xCan,yCurrent), image=imgRedDisc, anchor="nw")
光盘是在xCan的画布顶部创建的;电流。我现在要做的是制作光盘掉落到其目的地yCan的动画。我调用我的drop函数,该函数不断增加光盘的yCurrent,直到它通过递归和after()方法到达yCan:

def下降(光盘):
全球yCan,yCurrent
可以移动(光盘,0,1)
Y电流+=1
如果yCurrent
现在我的问题是,光盘的中间位置不显示,它只在几秒钟后直接显示在底部。 经过一些研究后,我添加了一行代码来更新画布:

def drop(disc):
    global yCan, yCurrent
    can.move(disc, 0, 1)
    yCurrent += 1
    can.update()
    if yCurrent < yCan:
        can.after(5, drop(disc))
def下降(光盘):
全球yCan,yCurrent
可以移动(光盘,0,1)
Y电流+=1
can.update()
如果yCurrent
现在我看到我的碟片掉了下来,但每次播放后都会变慢;光盘在我点击几秒钟后才开始掉落(这会触发光盘掉落)。另一个问题是,如果我通过快速双击触发两张碟片几乎疯狂地下落,第一张碟片会在中途停止下落,然后从画布上掉下来

我的问题是,如果没有
can.update()
,如何显示光盘掉落的每一步?
另外,我将每个光盘id存储在一个列表(discList)中,是否有更方便的方法来存储动态创建的画布图像?

在tkinter中制作动画的正确方法是使用一个函数来制作一帧动画,然后让它重复调用自己,直到出现某种终端条件

例如:

def move_object(obj_id):
    can.move(obj_id, 0, 1)
    x0,y0,x1,y1 = can.coords(obj_id)
    if y0 < yCan: 
        can.after(5, move_obj, obj_id)
。。。与此完全相同:

result = drop(disc)
can.after(5, drop)
注意到区别了吗?与
命令
属性类似,必须提供对函数的引用。但是,您正在调用函数,然后在
之后将结果提供给

下面是一个非常简单的示例:

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200)
canvas.pack(fill="both", expand=True)

ball = canvas.create_oval(50,0,100,50, fill="red")

def animate(obj_id):
    canvas.move(obj_id, 0, 3)
    x0,y0,x1,y1 = canvas.coords(obj_id)
    if y0 > canvas.winfo_height():
        canvas.coords(obj_id, 50,-50, 100, 0)
    canvas.after(50, animate, obj_id)

animate(ball)
root.mainloop()
result = drop(disc)
can.after(5, drop)
import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200)
canvas.pack(fill="both", expand=True)

ball = canvas.create_oval(50,0,100,50, fill="red")

def animate(obj_id):
    canvas.move(obj_id, 0, 3)
    x0,y0,x1,y1 = canvas.coords(obj_id)
    if y0 > canvas.winfo_height():
        canvas.coords(obj_id, 50,-50, 100, 0)
    canvas.after(50, animate, obj_id)

animate(ball)
root.mainloop()