[英]Upload image by clearing previous image
所以我有這個簡單的應用程序來上傳圖片,但現在我希望每次上傳新圖片時,之前的圖片都會被清除。 正在尋找解決方案,在此先感謝。
def open():
global my_image
root.filename = filedialog.askopenfilename(initialdir="e:/images", title="Select A File",
filetypes=(("png files", "*.png"), ("all files", "*.*")))
my_label = Label(root, text=root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
my_image_label = Label(image=my_image).pack()
my_btn = Button(root, text="Open File", command=open).pack()
您必須在 function 之外定義標簽,並在 function 內部對其進行更新,這樣可以避免每次都用新數據覆蓋標簽。 看看這里:
# Define the labels initially
my_image_label = Label(root)
my_label = Label(root)
def open_img():
path = filedialog.askopenfilename(initialdir="e:/images", title="Select A File",
filetypes=(("png files", "*.png"), ("all files", "*.*")))
my_label.config(text=path) # Update the label with the path
my_label.pack() # Pack it in there
my_image = ImageTk.PhotoImage(file=path) # Make an ImageTk instance
my_image_label.config(image=my_image) # Update the image label
my_image_label.pack() # Pack the label
my_image_label.img = my_img # Keep reference to the image
my_btn = Button(root, text="Open File", command=open_img)
my_btn.pack()
我都改變了什么?
我使用了小部件的config()
方法來幫助您編輯小部件的選項。
我還刪除了Image.open()
的用法,因為您可以通過使用ImageTk.PhotoImage
的file
關鍵字參數來實現相同的目的,它隱式調用Image.open()
。
我還刪除了global
並保留了對圖像的引用。
我還重命名了一些變量並將您的名稱更改為 function,因為open()
將覆蓋 python 的內置open()
function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.