为什么标签动画直到循环的最后一个值才起作用?



我是python的新手,最近一直在学习tkinter。所以我心想,使用grid_forget((函数,我可以删除一个小部件并重新定义它。我想到了这个动画,它可以改变标签的填充,从而创建空间(有点像移动标签,但不完全是这样(。但是,动画根本不起作用。程序将冻结,直到标签达到填充的最后一个值。我该怎么解决这个问题?或者有更好的方法来设置标签在屏幕中移动的动画吗?这是我的代码:

from tkinter import *
import time
root = Tk()
lbl = Label(root, text='------')
lbl.grid(row=0, column=0)

def animation():
padding = 0
while padding < 31:
lbl.grid_forget()
padding += 1
lbl.grid(row=0, column=0, padx=padding)
time.sleep(0.2)
# alternative: root.after(200, lambda: lbl.grid(row=0, column=0, padx=padding))

btn = Button(root, text='Animate', command=animation)
btn.grid(row=1, column=1)
root.mainloop()

您需要更新屏幕以显示更改。

下面是一个使用.update((方法的工作版本:

from tkinter import *
import time
root = Tk()
lbl = Label(root, text='------')
lbl.grid(row=0, column=0)

def animation():
padding = 0
while padding < 31:
lbl.grid_forget()
padding += 1
lbl.grid(row=0, column=0, padx=padding)
root.update()
time.sleep(0.2)
# alternative: root.after(200, lambda: lbl.grid(row=0, column=0, padx=padding))

btn = Button(root, text='Animate', command=animation)
btn.grid(row=1, column=1)
root.mainloop()

这是我在屏幕上制作动画的一种方法,我不明白你试图用上面的代码片段实现什么,我试着对它进行了一些更改,但我觉得这种方法要好得多,让你更好地控制你的窗口。

这使用了tkinter库中广泛使用的Canvas小部件。

Canvas是一个通用的小部件,你可以用它做很多事情。访问超链接以获得更清晰的

下面是一个如何在屏幕上创建文本的简短示例。

from tkinter import *
root = Tk()
root.title("My animation")
c = Canvas(root)
x = 20 
y = 20    #Instead of using row and column, you simply use x and y co-ordinates
#We will use these co-ordinates to show where the text is in the starting
my_text = c.create_text(x,y,text = '-----')
c.pack()
# This is all you need to create this text on your screen!
root.mainloop()

这个想法是你把你的画布放在你的窗户上,然后把你想要的东西放在上面

你可以添加更多的属性,让你的文本看起来更好。这里有一个关于它的深入教程

既然我们已经制作了您的文本小部件,现在是时候移动它了。让我们将其从初始位置20,20 移动到90,20

以下是我们将如何做到这一点。如果我们简单地将文本对象移动到90,90,我们不会看到任何动画,它只会直接在那里。所以我们要做的是首先在21,20创建它。然后是22,20。等等…

我们做得非常快,直到我们达到90,20

这看起来像是我们正在移动文本

from tkinter import *
import time
root = Tk()
root.title("My animation")
c = Canvas(root)
x = 20
y = 20    #Instead of using row and column, you simply use x and y co-ordinates
#We will use these co-ordinates to show where the text is in the starting
my_text = c.create_text(x,y,text = 'weee')
c.pack()
def animation():
y = 0.1
x = 0
for _ in range(1000):
c.move(my_text,x,y)
root.update()

anlabel = Button(root,text = 'Animate!',command = animation).pack()
root.mainloop()

这不仅适用于文本,也适用于画布上的所有内容(如其他图像(。画布上还有事件,可以让你在电脑上使用鼠标点击和其他键。

我对以前的代码做了一些更改,但它是可执行的,你可以自己尝试一下,看看它是如何工作的。增加time.sleep()中的值会使动画变慢,值越小,速度越快。

你确定你没有尝试做更像下面例子的事情吗?在你的一个小部件上设置填充动画会破坏你的其他显示。

from tkinter import *
import time
root = Tk()
lbl = Label(root, text='')
lbl.grid(row=0, column=0)

def animation(step=12):
step = 12 if step < 0 else step
lbl['text'] = '      ------      '[step:step+6]
root.after(200, lambda: animation(step-1))

Button(root, text='Animate', command=animation).grid(row=1, column=0, sticky='w')
root.mainloop()

最新更新