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

2024-04-19 19:17:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

谢谢


Tags: 答案图像tkinter地方gif闪屏
1条回答
网友
1楼 · 发布于 2024-04-19 19:17:15

下面是一个简单的例子,一些注意事项:

  1. tkinter不为gif设置动画,如果需要,可以手动执行(link
  2. 这是Python3的代码,在Python2中有些东西是不同的(导入名称,调用超级等等)
  3. 标签有背景,即使图像是透明的,也有解决方法(link
  4. 在本例中,我们获取一个图像(名为s.gif,放在代码文件旁边)并将其放置在(0,0)处,然后每隔2秒它在x和y方向移动10(帧的mod size)。当它被点击时,我们会显示一个splash框架一秒钟,然后将其删除(因为这是splash的要点)

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()

相关问题 更多 >