Python實(shí)現(xiàn)GUI圖片瀏覽的小程序
下面程序需要pillow庫(kù)。pillow是 Python 的第三方圖像處理庫(kù),需要安裝才能實(shí)用。pillow是PIL( Python Imaging Library)基礎(chǔ)上發(fā)展起來(lái)的,需要注意的是pillow庫(kù)安裝用pip install pillow,導(dǎo)包時(shí)要用PIL來(lái)導(dǎo)入。
一、簡(jiǎn)單的圖片查看程序
功能,使用了tkinter庫(kù)來(lái)創(chuàng)建一個(gè)窗口,用戶可以通過(guò)該窗口選擇一張圖片并在窗口中顯示。能調(diào)整窗口大小以適應(yīng)圖片。效果圖如下:
源碼如下:
import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk # 創(chuàng)建一個(gè)Tkinter窗口 root = tk.Tk() root.geometry("400x300") # 設(shè)置寬度為400像素,高度為300像素 root.title("Image Viewer") # 添加一個(gè)按鈕來(lái)選擇圖片 def open_image(): try: file_path = filedialog.askopenfilename() if file_path: image = Image.open(file_path) photo = ImageTk.PhotoImage(image) # 清除舊圖片 for widget in root.winfo_children(): if isinstance(widget, tk.Label): widget.destroy() label = tk.Label(root, image=photo) label.image = photo label.pack() # 調(diào)整窗口大小以適應(yīng)圖片 root.geometry("{}x{}".format(image.width, image.height)) except AttributeError: print("No image selected.") button = tk.Button(root, text="Open Image", command=open_image) button.pack() # 運(yùn)行窗口 root.mainloop()
此程序,創(chuàng)建一個(gè)tkinter窗口,設(shè)置窗口的大小為400x300像素,并設(shè)置窗口標(biāo)題為"Image Viewer"。
添加一個(gè)按鈕,當(dāng)用戶點(diǎn)擊該按鈕時(shí),會(huì)彈出文件選擇對(duì)話框,用戶可以選擇一張圖片文件。
選擇圖片后,程序會(huì)使用PIL庫(kù)中的Image.open方法打開(kāi)所選的圖片文件,并將其顯示在窗口中。
程序會(huì)在窗口中顯示所選的圖片,并在用戶選擇新圖片時(shí)清除舊圖片。
示例中,使用try-except塊來(lái)捕獲FileNotFoundError,該錯(cuò)誤會(huì)在用戶取消選擇圖片時(shí)觸發(fā)。當(dāng)用戶取消選擇圖片時(shí),會(huì)打印一條消息提示用戶沒(méi)有選擇圖片。這樣就可以避免因?yàn)槿∠x擇圖片而導(dǎo)致的報(bào)錯(cuò)。
二、圖片查看程序1
“Open Directory”按鈕用于指定一個(gè)目錄,窗體上再添加兩個(gè)按鈕:“Previous Image” 和“Next Image”,單擊這兩個(gè)按鈕實(shí)現(xiàn)切換顯示指定目錄中的圖片。這三個(gè)按鈕水平排列在頂部,在下方顯示圖片。如果所選圖片的尺寸超過(guò)了窗口的大小,程序會(huì)將圖片縮放到合適的尺寸以適應(yīng)窗口。效果圖如下:
源碼如下:
import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk import os class ImageViewer: def __init__(self, root): self.root = root self.root.geometry("400x350") self.root.title("Image Viewer") self.image_dir = "" self.image_files = [] self.current_index = 0 # 創(chuàng)建頂部按鈕框架 self.button_frame = tk.Frame(self.root) self.button_frame.pack(side="top") # 創(chuàng)建打開(kāi)目錄按鈕 self.open_button = tk.Button(self.button_frame, text="Open Directory", command=self.open_directory) self.open_button.pack(side="left") # 創(chuàng)建上一張圖片按鈕 self.prev_button = tk.Button(self.button_frame, text="Previous Image", command=self.show_previous_image) self.prev_button.pack(side="left") # 創(chuàng)建下一張圖片按鈕 self.next_button = tk.Button(self.button_frame, text="Next Image", command=self.show_next_image) self.next_button.pack(side="left") # 創(chuàng)建圖片顯示區(qū)域 self.image_label = tk.Label(self.root) self.image_label.pack() def open_directory(self): try: self.image_dir = filedialog.askdirectory() if self.image_dir: self.image_files = [f for f in os.listdir(self.image_dir) if f.endswith(".jpg") or f.endswith(".png") or f.endswith(".jfif")] self.current_index = 0 self.show_image() except tk.TclError: print("No directory selected.") def show_image(self): if self.image_files: image_path = os.path.join(self.image_dir, self.image_files[self.current_index]) image = Image.open(image_path) image.thumbnail((400, 300), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image) self.image_label.config(image=photo) self.image_label.image = photo def show_previous_image(self): if self.image_dir: if self.image_files: self.current_index = (self.current_index - 1) % len(self.image_files) self.show_image() else: print("Please open a directory first.") else: print("Please open a directory first.") def show_next_image(self): if self.image_dir: if self.image_files: self.current_index = (self.current_index + 1) % len(self.image_files) self.show_image() else: print("Please open a directory first.") else: print("Please open a directory first.") root = tk.Tk() app = ImageViewer(root) root.mainloop()
三、圖片查看程序2
窗體上有3個(gè)控件,列表框和按鈕和在窗體上左側(cè)上下放置,右側(cè)區(qū)域顯示圖片, “Open Directory”按鈕用于指定目錄中,列表用于放置指定目錄中的所有圖片文件名,點(diǎn)擊列表中的圖片文件名,圖片在右側(cè)不變形縮放顯示到窗體上(圖片縮放到合適的尺寸以適應(yīng)窗口),效果圖如下:
源碼如下:
import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk import os # 創(chuàng)建主窗口 root = tk.Tk() root.geometry("600x300") root.title("Image Viewer") # 創(chuàng)建一個(gè)Frame來(lái)包含按鈕和列表框 left_frame = tk.Frame(root) left_frame.pack(side=tk.LEFT, fill=tk.BOTH, padx=5, pady=5) # 創(chuàng)建一個(gè)Frame來(lái)包含圖片顯示區(qū)域 right_frame = tk.Frame(root) right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True) # 創(chuàng)建一個(gè)列表框來(lái)顯示文件名 listbox = tk.Listbox(left_frame) listbox.pack(fill=tk.BOTH, expand=True) # 創(chuàng)建一個(gè)滾動(dòng)條并將其與列表框關(guān)聯(lián) scrollbar = tk.Scrollbar(root, orient=tk.VERTICAL) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) scrollbar.config(command=listbox.yview) listbox.config(yscrollcommand=scrollbar.set) # 創(chuàng)建一個(gè)標(biāo)簽來(lái)顯示圖片 image_label = tk.Label(right_frame) image_label.pack(fill=tk.BOTH, expand=True) # 函數(shù):打開(kāi)目錄并列出圖片文件 def open_directory(): directory = filedialog.askdirectory() if directory: # 清空列表框 listbox.delete(0, tk.END) # 列出目錄中的所有圖片文件 for file in os.listdir(directory): if file.lower().endswith(('.jpg', '.jpeg', '.png', '.gif','.jfif')): listbox.insert(tk.END, file) # 保存當(dāng)前目錄 open_directory.current_directory = directory # 函數(shù):在右側(cè)顯示選中的圖片 def show_selected_image(event): if not hasattr(open_directory, 'current_directory'): return # 獲取選中的文件名 selected_file = listbox.get(listbox.curselection()) # 構(gòu)建完整的文件路徑 file_path = os.path.join(open_directory.current_directory, selected_file) # 打開(kāi)圖片并進(jìn)行縮放 image = Image.open(file_path) image.thumbnail((right_frame.winfo_width(), right_frame.winfo_height()), Image.ANTIALIAS) # 用PIL的PhotoImage顯示圖片 photo = ImageTk.PhotoImage(image) image_label.config(image=photo) image_label.image = photo # 保存引用,防止被垃圾回收 # 創(chuàng)建“Open Directory”按鈕 open_button = tk.Button(left_frame, text="Open Directory", command=open_directory) open_button.pack(fill=tk.X) # 綁定列表框選擇事件 listbox.bind('<<ListboxSelect>>', show_selected_image) # 運(yùn)行主循環(huán) root.mainloop()
以上就是Python實(shí)現(xiàn)GUI圖片瀏覽的小程序的詳細(xì)內(nèi)容,更多關(guān)于Python GUI圖片瀏覽的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python GoogleIt庫(kù)實(shí)現(xiàn)在Google搜索引擎上快速搜索
這篇文章主要為大家介紹了python GoogleIt庫(kù)實(shí)現(xiàn)在Google搜索引擎上快速搜索功能探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01Python?Panda中索引和選擇?series?的數(shù)據(jù)
這篇文章主要介紹了Python?Panda中索引和選擇series的數(shù)據(jù),文章通過(guò)圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09Python中有哪些關(guān)鍵字及關(guān)鍵字的用法
這篇文章主要介紹了Python中有哪些關(guān)鍵字及關(guān)鍵字的用法,分享python中常用的關(guān)鍵字,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-02-02python中cryptography庫(kù)的實(shí)現(xiàn)
本文主要介紹了python中cryptography庫(kù)的實(shí)現(xiàn),包括Fernet、hash、AES、RSA等加密算法的使用,具有一定的參加價(jià)值,感興趣的可以了解一下2025-01-01為什么Python中沒(méi)有"a++"這種寫(xiě)法
一開(kāi)始學(xué)習(xí) Python 的時(shí)候習(xí)慣性的使用 C 中的 a++ 這種寫(xiě)法,發(fā)現(xiàn)會(huì)報(bào) SyntaxError: invalid syntax 錯(cuò)誤,為什么 Python 沒(méi)有自增運(yùn)算符的這種寫(xiě)法呢?下面小編給大家?guī)?lái)本文幫助大家了解下這方面的知識(shí)2018-11-11TensorFlow實(shí)現(xiàn)隨機(jī)訓(xùn)練和批量訓(xùn)練的方法
本篇文章主要介紹了TensorFlow實(shí)現(xiàn)隨機(jī)訓(xùn)練和批量訓(xùn)練的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Python3自動(dòng)安裝第三方庫(kù),跟pip說(shuō)再見(jiàn)
很多朋友私信小編Python安裝第三方庫(kù)安裝技巧,在這就不一一回復(fù)大家了,今天小編給大家分享一篇教程關(guān)于Python自動(dòng)安裝第三方庫(kù)的小技巧,本文以安裝plotly為例給大家詳細(xì)講解,感興趣的朋友跟隨小編一起看看吧2021-10-10