在 tkinter 中制作动画的模式是使用after
一次安排一帧动画。它看起来像这样,在哪里fps
定义为每秒所需的帧数,并且widget
是一个 tkinter 小部件:
def animate():
<draw one frame of animation>
widget.after(int(1000/fps), animate)
对于选框,最简单的解决方案之一是使用画布,因为它具有方便的功能move
可用于从右向左移动文本的方法。
这是一个例子:
import tkinter as tk
class Marquee(tk.Canvas):
def __init__(self, parent, text, margin=2, borderwidth=1, relief='flat', fps=30):
super().__init__(parent, borderwidth=borderwidth, relief=relief)
self.fps = fps
# start by drawing the text off screen, then asking the canvas
# how much space we need. Use that to compute the initial size
# of the canvas.
text = self.create_text(0, -1000, text=text, anchor="w", tags=("text",))
(x0, y0, x1, y1) = self.bbox("text")
width = (x1 - x0) + (2*margin) + (2*borderwidth)
height = (y1 - y0) + (2*margin) + (2*borderwidth)
self.configure(width=width, height=height)
# start the animation
self.animate()
def animate(self):
(x0, y0, x1, y1) = self.bbox("text")
if x1 < 0 or y0 < 0:
# everything is off the screen; reset the X
# to be just past the right margin
x0 = self.winfo_width()
y0 = int(self.winfo_height()/2)
self.coords("text", x0, y0)
else:
self.move("text", -1, 0)
# do again in a few milliseconds
self.after_id = self.after(int(1000/self.fps), self.animate)
root = tk.Tk()
marquee = Marquee(root, text="Hello, world", borderwidth=1, relief="sunken")
marquee.pack(side="top", fill="x", pady=20)
root.mainloop()