最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實現GUI圖片瀏覽的小程序

 更新時間:2023年12月15日 11:01:08   作者:軟件技術愛好者  
這篇文章主要介紹了Python實現GUI圖片瀏覽程序,程序的實現需要pillow庫,pillow是 Python 的第三方圖像處理庫,需要安裝才能實用,文中通過代碼示例給大家介紹的非常詳細,需要的朋友可以參考下

下面程序需要pillow庫。pillow是 Python 的第三方圖像處理庫,需要安裝才能實用。pillow是PIL( Python Imaging Library)基礎上發(fā)展起來的,需要注意的是pillow庫安裝用pip install pillow,導包時要用PIL來導入。

一、簡單的圖片查看程序

功能,使用了tkinter庫來創(chuàng)建一個窗口,用戶可以通過該窗口選擇一張圖片并在窗口中顯示。能調整窗口大小以適應圖片。效果圖如下:

源碼如下:

import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
 
# 創(chuàng)建一個Tkinter窗口
root = tk.Tk()
root.geometry("400x300")  # 設置寬度為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()
 
            # 調整窗口大小以適應圖片
            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窗口,設置窗口的大小為400x300像素,并設置窗口標題為"Image Viewer"。

添加一個按鈕,當用戶點擊該按鈕時,會彈出文件選擇對話框,用戶可以選擇一張圖片文件。

選擇圖片后,程序會使用PIL庫中的Image.open方法打開所選的圖片文件,并將其顯示在窗口中。

程序會在窗口中顯示所選的圖片,并在用戶選擇新圖片時清除舊圖片。

示例中,使用try-except塊來捕獲FileNotFoundError,該錯誤會在用戶取消選擇圖片時觸發(fā)。當用戶取消選擇圖片時,會打印一條消息提示用戶沒有選擇圖片。這樣就可以避免因為取消選擇圖片而導致的報錯。

二、圖片查看程序1

“Open Directory”按鈕用于指定一個目錄,窗體上再添加兩個按鈕:“Previous Image” 和“Next Image”,單擊這兩個按鈕實現切換顯示指定目錄中的圖片。這三個按鈕水平排列在頂部,在下方顯示圖片。如果所選圖片的尺寸超過了窗口的大小,程序會將圖片縮放到合適的尺寸以適應窗口。效果圖如下:

源碼如下:

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個控件,列表框和按鈕和在窗體上左側上下放置,右側區(qū)域顯示圖片, “Open Directory”按鈕用于指定目錄中,列表用于放置指定目錄中的所有圖片文件名,點擊列表中的圖片文件名,圖片在右側不變形縮放顯示到窗體上(圖片縮放到合適的尺寸以適應窗口),效果圖如下:

源碼如下:

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)建一個滾動條并將其與列表框關聯
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)
 
# 函數:打開目錄并列出圖片文件
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
 
# 函數:在右側顯示選中的圖片
def show_selected_image(event):
    if not hasattr(open_directory, 'current_directory'):
        return
    # 獲取選中的文件名
    selected_file = listbox.get(listbox.curselection())
    # 構建完整的文件路徑
    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實現GUI圖片瀏覽的小程序的詳細內容,更多關于Python GUI圖片瀏覽的資料請關注腳本之家其它相關文章!

相關文章

  • 基于OpenCV實現視頻循環(huán)播放

    基于OpenCV實現視頻循環(huán)播放

    這篇文章主要為大家介紹了如何利用OpenCV實現視頻的循環(huán)播放,本文為大家提供了兩種方式,一個是利用Python語言實現,一個是利用C++語言實現,需要的可以參考一下
    2022-02-02
  • Python進程和線程之多線程的使用及說明

    Python進程和線程之多線程的使用及說明

    Python多線程通過threading模塊實現,主線程默認運行,子線程由Thread類創(chuàng)建并啟動,線程共享變量易引發(fā)數據混亂,需用Lock同步,但鎖可能降低效率或導致死鎖,(79字)
    2025-09-09
  • Python3.5 Pandas模塊之Series用法實例分析

    Python3.5 Pandas模塊之Series用法實例分析

    這篇文章主要介紹了Python3.5 Pandas模塊之Series用法,結合實例形式分析了Python3.5中Pandas模塊的Series結構原理、創(chuàng)建、獲取、運算等相關操作技巧與注意事項,需要的朋友可以參考下
    2019-04-04
  • Python數據集切分實例

    Python數據集切分實例

    今天小編就為大家分享一篇Python數據集切分實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • python實現將文本轉換成語音的方法

    python實現將文本轉換成語音的方法

    這篇文章主要介紹了python實現將文本轉換成語音的方法,涉及Python中pyTTS模塊的相關使用技巧,需要的朋友可以參考下
    2015-05-05
  • 在Python中使用MySQL--PyMySQL的基本使用方法

    在Python中使用MySQL--PyMySQL的基本使用方法

    PyMySQL 是在 Python3.x 版本中用于連接 MySQL 服務器的一個庫,Python2中則使用mysqldb。這篇文章主要介紹了在Python中使用MySQL--PyMySQL的基本使用,需要的朋友可以參考下
    2019-11-11
  • PyCharm 設置SciView工具窗口的方法

    PyCharm 設置SciView工具窗口的方法

    今天小編就為大家分享一篇PyCharm 設置SciView工具窗口的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • 最簡單的matplotlib安裝教程(小白)

    最簡單的matplotlib安裝教程(小白)

    這篇文章主要介紹了最簡單的matplotlib安裝教程(小白),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-07-07
  • Django2.1.7 查詢數據返回json格式的實現

    Django2.1.7 查詢數據返回json格式的實現

    這篇文章主要介紹了Django2.1.7 查詢數據返回json格式的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-12-12
  • Python ORM框架SQLAlchemy學習筆記之安裝和簡單查詢實例

    Python ORM框架SQLAlchemy學習筆記之安裝和簡單查詢實例

    這篇文章主要介紹了Python ORM框架SQLAlchemy學習筆記之安裝和簡單查詢實例,簡明入門教程,需要的朋友可以參考下
    2014-06-06

最新評論

东宁县| 瑞丽市| 城步| 珲春市| 商河县| 西林县| 抚州市| 望都县| 白沙| 克东县| 平和县| 社旗县| 饶阳县| 昂仁县| 新营市| 龙江县| 建水县| 扶余县| 邯郸县| 伽师县| 红河县| 五莲县| 沁阳市| 凤阳县| 康马县| 财经| 自贡市| 喀喇沁旗| 格尔木市| 武冈市| 富川| 自贡市| 娱乐| 图木舒克市| 西安市| 岢岚县| 旅游| 崇左市| 潜山县| 汪清县| 乌拉特中旗|