用python写一个简易图片浏览器
时间: 2023-07-20 22:05:41 浏览: 54
好的,以下是一个简单的Python图片浏览器的代码示例:
```python
from tkinter import *
from PIL import ImageTk, Image
import os
# 设置窗口和图片大小
WINDOW_SIZE = "500x500"
IMG_SIZE = (400, 400)
# 获取当前文件夹下的所有图片
def get_image_list():
image_list = []
for file in os.listdir():
if file.endswith(".jpg") or file.endswith(".png"):
image_list.append(file)
return image_list
# 显示图片
def show_image(image_path):
img = Image.open(image_path)
img = img.resize(IMG_SIZE, Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)
label = Label(image=photo)
label.image = photo
label.place(x=50, y=50)
# 切换图片
def next_image():
global image_index
image_index += 1
if image_index >= len(image_list):
image_index = 0
show_image(image_list[image_index])
def previous_image():
global image_index
image_index -= 1
if image_index < 0:
image_index = len(image_list) - 1
show_image(image_list[image_index])
# 初始化窗口
root = Tk()
root.geometry(WINDOW_SIZE)
root.title("Image Viewer")
# 获取图片列表并显示第一张图片
image_list = get_image_list()
image_index = 0
if image_list:
show_image(image_list[0])
# 添加按钮
previous_button = Button(root, text="Previous", command=previous_image)
previous_button.place(x=50, y=450)
next_button = Button(root, text="Next", command=next_image)
next_button.place(x=400, y=450)
# 运行窗口
root.mainloop()
```
该代码使用了`tkinter`和`PIL`库来创建窗口并显示图片。首先通过`get_image_list()`函数获取当前文件夹下所有的图片文件,然后通过`show_image()`函数来显示图片。`next_image()`和`previous_image()`函数用于切换图片。
在初始化窗口之后,我们获取了图片列表并显示第一张图片。之后,我们添加了两个按钮,`previous_button`和`next_button`,并将它们绑定到对应的函数。最后,我们运行窗口并进入主循环,等待用户的操作。
请注意,该代码只是一个简化的示例,可能需要根据具体需求进行修改。