如何使GIF在窗口中移动并响应点击

时间:2018-09-14 06:14:20

标签: python tkinter

在Tkinter中,我需要每隔2秒让GIF图像在窗口中移动一次,并在单击它时显示启动屏幕。我完全不知道如何导入图像并使其移动/响应单击,并且在其他地方找不到直接的答案。

谢谢

1 个答案:

答案 0 :(得分:1)

这是一个简单的例子,有一些注意事项:

  1. tkinter不会为gif设置动画,如果需要,您可以手动进行(link
  2. 这是Python3代码,在Python2中有些不同(导入名称,调用super等)。
  3. 即使图像是透明的,标签也有背景,有一些解决方法(link
  4. 在此示例中,我们拍摄一张图像(名为s.gif并放置在代码文件旁边),并将其放置在(0,0)处,然后每2秒在x和y(帧的mod大小)中移动10秒。单击它时,我们会显示一个启动画面,然后将其删除(因为这是“启动”的重点)

from PIL import Image, ImageTk
from tkinter import Tk, BOTH, Toplevel
from tkinter.ttk import Frame, Label


class Example(Frame):
    def __init__(self, root):
        super().__init__()
        self._root = root

        # Init class variables
        self._size = 300
        self._image_label = None
        self.image_place = 0

        self.init_ui()

        # Acutally run the UI
        root.mainloop()

    def init_ui(self):
        # Init general layour
        self._root.geometry("{size}x{size}+{size}+{size}".format(size=self._size))
        self.master.title("Absolute positioning")
        self.pack(fill=BOTH, expand=1)  # show this frame

        # Setup image
        path_to_iamge = "s.gif"
        s_image = ImageTk.PhotoImage(Image.open(path_to_iamge).convert("RGBA")) # Convert to RGBA to get transparency
        # place image in a label, we are going to be moving this frame around
        self._image_label = Label(self, image=s_image)
        self._image_label.image = s_image
        # Make image clickable, running show_splash when clicked
        self._image_label.bind("<Button-1>", self._show_splash)

        self._place_image_label()

    def _place_image_label(self):
        # Show image label
        self._image_label.place(x=self.image_place, y=self.image_place)
        # increase image coordination for next time
        self.image_place = (self.image_place + 10) % self._size
        # reschedule to run again in 2 seconds
        self._root.after(2000, self._place_image_label)

    def _show_splash(self, event):
        splash = Toplevel(self)
        # update UI with splash
        self.update()
        # schedule to close splash after a 1 second
        self._root.after(1000, lambda: splash.destroy())


def main():
    Example(Tk())

if __name__ == '__main__':
    main()