📌  相关文章
📜  如何在 python 中的 tkinter 中添加上一个和下一个(1)

📅  最后修改于: 2023-12-03 15:24:20.089000             🧑  作者: Mango

如何在 Python 的 tkinter 中添加上一个和下一个

在使用 python 的 tkinter 模块创建 GUI 时,我们常常需要添加类似于照片浏览器中的上一个和下一个按钮。本文将介绍如何在 tkinter 中创建这样的按钮。

创建上一个和下一个按钮

在 tkinter 中创建按钮需要使用 tkinter.Button() 函数,其中 command 参数是指定按钮被点击时要执行的函数。

为了实现上一个和下一个按钮的功能,我们需要先准备好一组需要切换显示的图片,并显示其中的任意一张。同时,我们需要记录当前显示的图片在列表中的位置 current_image_index,初始值可以随便设置一个合法值。

import tkinter as tk
from PIL import Image, ImageTk

# 准备需要展示的图片
images = [Image.open('image1.jpg'), Image.open('image2.jpg'), Image.open('image3.jpg')]

# 记录当前显示的图片在列表中的位置
current_image_index = 0

# 展示任意一张图片
root = tk.Tk()
image = ImageTk.PhotoImage(images[current_image_index])
image_label = tk.Label(root, image=image)
image_label.pack()

接下来,我们要创建两个按钮:上一个和下一个。按钮的点击事件函数中需要切换到上一个或下一个图片,并更新 current_image_index 的值。

为了避免越界,我们需要在按钮的点击事件处理函数中先判断一下是否已经到了列表的开头或结尾,如果是,则直接返回。如果没有到达开头或结尾,则切换到上一个或下一个图片,并在 image_label 中更新展示的图片。

def show_previous_image():
    global current_image_index
    if current_image_index == 0:
        return
    current_image_index -= 1
    image = ImageTk.PhotoImage(images[current_image_index])
    image_label.configure(image=image)
    image_label.image = image

def show_next_image():
    global current_image_index
    if current_image_index == len(images) - 1:
        return
    current_image_index += 1
    image = ImageTk.PhotoImage(images[current_image_index])
    image_label.configure(image=image)
    image_label.image = image

# 创建上一个和下一个按钮
previous_button = tk.Button(root, text="上一个", command=show_previous_image)
previous_button.pack(side=tk.LEFT)
next_button = tk.Button(root, text="下一个", command=show_next_image)
next_button.pack(side=tk.LEFT)

# 进入主循环
root.mainloop()

现在,我们就成功地创建了一个带有上一个和下一个按钮的图片浏览器。

总结

本文介绍了如何在 python 的 tkinter 中创建带有上一个和下一个按钮的图片浏览器。我们需要先准备好要展示的图片,然后创建上一个和下一个按钮,在按钮的点击事件函数中使用 global 关键字来更新 current_image_index 的值,并在 image_label 中更新展示的图片。