当前位置: 首页 > news >正文

自制简单的图片查看器(python)

图片格式:支持常见的图片格式(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() 

相关文章:

  • 用deepseek学大模型08-循环神经网络
  • CoCo AI APP 初体验:开启智能知识管理新篇章
  • 单例模式、构造函数、左值右值
  • 数控机床设备分布式健康监测与智能维护系统MTAgent
  • leetcode 1594. 矩阵的最大非负积
  • Java8适配的markdown转换html工具(FlexMark)
  • STL介绍1:vector、pair、string、queue、map
  • 深度学习之图像回归(二)
  • python windows services demo
  • 条款13:以对象管理资源
  • C++ 的时间库之二:Ratio
  • 【Elasticsearch】分页查询
  • 自然语言处理入门1——单词的表示和距离
  • el-table的hasChildren不生效?子级没数据还显示箭头号?树形数据无法展开和收缩
  • 数据治理中 大数据处理一般都遵循哪些原则
  • idea日常报错之UTF-8不可映射的字符
  • 关于如何利用群晖Docker搭建Project Zomboid(僵尸毁灭工程)私人服务器-保姆级教程
  • P2814 家谱 C++
  • MVTEC数据集笔记
  • 第435场周赛:奇偶频次间的最大差值 Ⅰ、K 次修改后的最大曼哈顿距离、使数组包含目标值倍数的最少增量、奇偶频次间的最大差值 Ⅱ
  • 观察|天空之外的战场:官方叙事、新闻与社交平台中的印巴冲突
  • 国际足联女子世界杯再次扩军,2031年起增至48支球队
  • 4月金融数据前瞻:受去年低基数因素影响,社融增量有望同比大幅多增
  • 101条关于减重的知识,其中一定有你不知道的
  • 全国人大常委会启动食品安全法执法检查
  • 陕西永寿4岁女童被蜜蜂蜇伤致死,当地镇政府介入处理