当前位置: 代码网 > it编程>前端脚本>Python > 使用Python实现一个图片查看器

使用Python实现一个图片查看器

2025年02月18日 Python 我要评论
效果图图片格式:支持常见的图片格式(jpg、png、bmp、gif)。完整代码import osimport tkinter as tkfrom tkinter import filedialog,

效果图

图片格式:支持常见的图片格式(jpg、png、bmp、gif)。

完整代码

import os
import tkinter as tk
from tkinter import filedialog, messagebox
from pil import image, imagetk
 
class imageviewer:
    def __init__(self, root):
        self.root = root
        self.root.title("图片查看器")
        self.root.geometry("800x600")
        self.root.configure(bg="#2e3440")  # 设置背景颜色
 
        # 当前图片路径
        self.current_image_path = none
        self.image = none
        self.photo = none
        self.scale_factor = 1.0
        self.is_auto_scaling = true  # 是否自动缩放
 
        # 创建界面
        self.create_widgets()
 
    def create_widgets(self):
        """创建界面组件"""
        # 顶部工具栏
        toolbar = tk.frame(self.root, bg="#3b4252")  # 工具栏背景颜色
        toolbar.pack(side=tk.top, fill=tk.x)
 
        # 打开按钮
        btn_open = tk.button(toolbar, text="打开", command=self.open_image, bg="#81a1c1", fg="white", activebackground="#5e81ac", activeforeground="white", font=("微软雅黑", 12))
        btn_open.pack(side=tk.left, padx=5, pady=5)
 
        # 放大按钮
        btn_zoom_in = tk.button(toolbar, text="放大", command=self.zoom_in, bg="#81a1c1", fg="white", activebackground="#5e81ac", activeforeground="white", font=("微软雅黑", 12))
        btn_zoom_in.pack(side=tk.left, padx=5, pady=5)
 
        # 缩小按钮
        btn_zoom_out = tk.button(toolbar, text="缩小", command=self.zoom_out, bg="#81a1c1", fg="white", activebackground="#5e81ac", activeforeground="white", font=("微软雅黑", 12))
        btn_zoom_out.pack(side=tk.left, padx=5, pady=5)
 
        # 图片显示区域
        self.canvas = tk.canvas(self.root, bg="#2e3440", highlightthickness=0)
        self.canvas.pack(fill=tk.both, expand=true)
 
        # 绑定窗口大小变化事件
        self.root.bind("<configure>", self.on_window_resize)
 
    def open_image(self):
        """打开图片"""
        file_path = filedialog.askopenfilename(
            title="选择图片",
            filetypes=[("图片文件", "*.jpg *.jpeg *.png *.bmp *.gif")]
        )
        if file_path:
            self.current_image_path = file_path
            self.load_image()
 
    def load_image(self):
        """加载图片"""
        try:
            self.image = image.open(self.current_image_path)
            self.scale_factor = 1.0
            self.is_auto_scaling = true  # 加载图片时启用自动缩放
            self.update_image()
        except exception as e:
            messagebox.showerror("错误", f"无法加载图片: {str(e)}")
 
    def update_image(self):
        """更新显示的图片"""
        if self.image:
            # 计算缩放后的尺寸
            canvas_width = self.canvas.winfo_width()
            canvas_height = self.canvas.winfo_height()
            image_width, image_height = self.image.size
 
            if self.is_auto_scaling:
                # 自动缩放时计算缩放比例
                width_ratio = canvas_width / image_width
                height_ratio = canvas_height / image_height
                self.scale_factor = min(width_ratio, height_ratio)
 
            # 缩放图片
            width = int(image_width * self.scale_factor)
            height = int(image_height * self.scale_factor)
            resized_image = self.image.resize((width, height), image.resampling.lanczos)
            self.photo = imagetk.photoimage(resized_image)
 
            # 清除画布并显示图片
            self.canvas.delete("all")
            self.canvas.create_image(
                canvas_width // 2,
                canvas_height // 2,
                anchor=tk.center,
                image=self.photo
            )
 
    def zoom_in(self):
        """放大图片"""
        if self.image:
            self.is_auto_scaling = false  # 手动缩放时禁用自动缩放
            self.scale_factor *= 1.2
            self.update_image()
 
    def zoom_out(self):
        """缩小图片"""
        if self.image:
            self.is_auto_scaling = false  # 手动缩放时禁用自动缩放
            self.scale_factor /= 1.2
            self.update_image()
 
    def on_window_resize(self, event):
        """窗口大小变化时自动调整图片大小"""
        if self.image and self.is_auto_scaling:
            self.update_image()
 
if __name__ == "__main__":
    root = tk.tk()
    app = imageviewer(root)
    root.mainloop() 

到此这篇关于使用python实现一个图片查看器的文章就介绍到这了,更多相关python图片查看器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com