Python實現(xiàn)GUI圖片瀏覽的小程序
下面程序需要pillow庫。pillow是 Python 的第三方圖像處理庫,需要安裝才能實用。pillow是PIL( Python Imaging Library)基礎(chǔ)上發(fā)展起來的,需要注意的是pillow庫安裝用pip install pillow,導包時要用PIL來導入。
一、簡單的圖片查看程序
功能,使用了tkinter庫來創(chuàng)建一個窗口,用戶可以通過該窗口選擇一張圖片并在窗口中顯示。能調(diào)整窗口大小以適應(yīng)圖片。效果圖如下:

源碼如下:
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
# 創(chuàng)建一個Tkinter窗口
root = tk.Tk()
root.geometry("400x300") # 設(shè)置寬度為400像素,高度為300像素
root.title("Image Viewer")
# 添加一個按鈕來選擇圖片
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()
# 運行窗口
root.mainloop()此程序,創(chuàng)建一個tkinter窗口,設(shè)置窗口的大小為400x300像素,并設(shè)置窗口標題為"Image Viewer"。
添加一個按鈕,當用戶點擊該按鈕時,會彈出文件選擇對話框,用戶可以選擇一張圖片文件。
選擇圖片后,程序會使用PIL庫中的Image.open方法打開所選的圖片文件,并將其顯示在窗口中。
程序會在窗口中顯示所選的圖片,并在用戶選擇新圖片時清除舊圖片。
示例中,使用try-except塊來捕獲FileNotFoundError,該錯誤會在用戶取消選擇圖片時觸發(fā)。當用戶取消選擇圖片時,會打印一條消息提示用戶沒有選擇圖片。這樣就可以避免因為取消選擇圖片而導致的報錯。
二、圖片查看程序1
“Open Directory”按鈕用于指定一個目錄,窗體上再添加兩個按鈕:“Previous Image” 和“Next Image”,單擊這兩個按鈕實現(xiàn)切換顯示指定目錄中的圖片。這三個按鈕水平排列在頂部,在下方顯示圖片。如果所選圖片的尺寸超過了窗口的大小,程序會將圖片縮放到合適的尺寸以適應(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)建打開目錄按鈕
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個控件,列表框和按鈕和在窗體上左側(cè)上下放置,右側(cè)區(qū)域顯示圖片, “Open Directory”按鈕用于指定目錄中,列表用于放置指定目錄中的所有圖片文件名,點擊列表中的圖片文件名,圖片在右側(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)建一個Frame來包含按鈕和列表框
left_frame = tk.Frame(root)
left_frame.pack(side=tk.LEFT, fill=tk.BOTH, padx=5, pady=5)
# 創(chuàng)建一個Frame來包含圖片顯示區(qū)域
right_frame = tk.Frame(root)
right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
# 創(chuàng)建一個列表框來顯示文件名
listbox = tk.Listbox(left_frame)
listbox.pack(fill=tk.BOTH, expand=True)
# 創(chuà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)建一個標簽來顯示圖片
image_label = tk.Label(right_frame)
image_label.pack(fill=tk.BOTH, expand=True)
# 函數(shù):打開目錄并列出圖片文件
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)
# 保存當前目錄
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)
# 打開圖片并進行縮放
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)
# 運行主循環(huán)
root.mainloop()以上就是Python實現(xiàn)GUI圖片瀏覽的小程序的詳細內(nèi)容,更多關(guān)于Python GUI圖片瀏覽的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python GoogleIt庫實現(xiàn)在Google搜索引擎上快速搜索
這篇文章主要為大家介紹了python GoogleIt庫實現(xiàn)在Google搜索引擎上快速搜索功能探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
Python?Panda中索引和選擇?series?的數(shù)據(jù)
這篇文章主要介紹了Python?Panda中索引和選擇series的數(shù)據(jù),文章通過圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09
Python中有哪些關(guān)鍵字及關(guān)鍵字的用法
這篇文章主要介紹了Python中有哪些關(guān)鍵字及關(guān)鍵字的用法,分享python中常用的關(guān)鍵字,本文結(jié)合示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
TensorFlow實現(xiàn)隨機訓練和批量訓練的方法
本篇文章主要介紹了TensorFlow實現(xiàn)隨機訓練和批量訓練的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04

