【问题标题】:How to make a GIF move across the window and respond to a click [closed]如何使 GIF 在窗口中移动并响应点击 [关闭]
【发布时间】:2018-09-14 06:14:19
【问题描述】:

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

谢谢

【问题讨论】:

  • 您可以更准确地提出您的问题,并写一些关于您尝试过的内容和遇到的问题。由于您的一般性问题,您获得了一些反对票。如果我的回答对您有帮助,您可以点赞并接受它作为正确答案。如果你没有,你可以发表评论,我可能会回来查看(或者其他人可能会看到它)。

标签: python tkinter


【解决方案1】:

这是一个简单的例子,一些注释:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多