PHP前端开发

Python tkinter GUI动态改变图像

百变鹏仔 1天前 #Python
文章标签 图像
问题内容

我来自java,只想创建一个带有图片的图形用户界面,但是图片正在动态变化,我不知道它将是哪张图片......但它不起作用,我只能创建一个图像并且无法在 root.mainloop() 之外更改它并收到大量错误消息...有人知道如何动态更改图像吗?非常感谢

import tkinter as tkfrom PIL import Image, ImageTkdef add_image_to_gui(root, image_path):    # Load image    image = Image.open(image_path)    # Convert image to Tkinter-compatible format    tk_image = ImageTk.PhotoImage(image)    # Create label and display image    image_label = tk.Label(root, image=tk_image)    image_label.image = tk_image  # Keep reference to the image to prevent it from being garbage collected    image_label.pack()def create_gui(window_title, window_size, image_path):    # Create Tkinter window    root = tk.Tk()    root.title(window_title)    root.geometry(window_size)    # Add image    add_image_to_gui(root, image_path)    # Start Tkinter event loop    root.mainloop()    return rootif __name__ == "__main__":    window_title = "Simple GUI"    window_size = "1495x1020"    image_path = "Bilder/Hauptfenster.png"    root = create_gui(window_title, window_size, image_path)

chatgpt,谷歌搜索,但似乎没有人像我一样遇到同样的问题......


正确答案


为了在一段时间后切换图像,您需要调用某种类型的函数来更改它。由于此 gui 没有按钮,最简单的方法是使用 tkinter.tk().after 安排将来的更新,并让该函数更改标签图像。

下面是一些示例代码,展示了如何通过最少的修改来实现这一目标:

编辑:更新注释中的附加信息,另一个函数将提供文件路径,对 function_that_yields_new_image_paths 的调用将被替换。

立即学习“Python免费学习笔记(深入)”;

import tkinter as tkfrom PIL import Image, ImageTkdef add_image_to_gui(root):    image_label = tk.Label(root)    image_label.pack()    return image_labeldef update_image(root, image_label):    image = Image.open(function_that_yields_new_image_paths())    tk_image = ImageTk.PhotoImage(image)    image_label.configure(image=tk_image)    image_label.image = tk_image    root.after(1000, update_image, root, image_label)def function_that_yields_new_image_paths():    import numpy    image_path1 = "a.png"    image_path2 = "b.png"    return numpy.random.choice((image_path1, image_path2))def create_gui(window_title, window_size):    # Create Tkinter window    root = tk.Tk()    root.title(window_title)    root.geometry(window_size)    # Add image    image_label = add_image_to_gui(root)    root.after(1, update_image, root, image_label)    # Start Tkinter event loop    root.mainloop()    return rootif __name__ == "__main__":    window_title = "Simple GUI"    window_size = "1495x1020"    root = create_gui(window_title, window_size)

如果您有任何疑问,请告诉我。