在Tkinter中,我需要每隔2秒让GIF图像在窗口中移动一次,并在单击它时显示启动屏幕。我完全不知道如何导入图像并使其移动/响应单击,并且在其他地方找不到直接的答案。
谢谢
答案 0 :(得分:1)
这是一个简单的例子,有一些注意事项:
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()