首頁 >後端開發 >Python教學 >Python tkinter GUI動態改變影像

Python tkinter GUI動態改變影像

WBOY
WBOY轉載
2024-02-09 14:45:041220瀏覽

Python tkinter GUI动态改变图像

問題內容

我來自java,只想創建一個帶有圖片的圖形用戶界面,但是圖片正在動態變化,我不知道它將是哪張圖片......但它不起作用,我只能創建一個圖像並且無法在root.mainloop() 之外更改它並收到大量錯誤訊息... 有人知道如何動態更改圖像嗎? 非常感謝

import tkinter as tk
from PIL import Image, ImageTk

def 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 root

if __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 的呼叫將被替換。

import tkinter as tk
from PIL import Image, ImageTk

def add_image_to_gui(root):
    image_label = tk.Label(root)
    image_label.pack()
    return image_label

def 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 root

if __name__ == "__main__":
    window_title = "Simple GUI"
    window_size = "1495x1020"

    root = create_gui(window_title, window_size)

如果您有任何疑問,請告訴我。

以上是Python tkinter GUI動態改變影像的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除