用Python创建一个 Sideshow 应用程序
在本文中,我们将创建一个幻灯片应用程序,即无需手动更改或单击即可查看下一张图像。
所需模块:
- Tkinter: tkinter 包(“Tk 接口”)是 Tk GUI 工具包的标准Python接口。
- Pillow: Python图像库为您的Python解释器添加了图像处理功能。该库提供了广泛的文件格式支持、高效的内部表示和相当强大的图像处理能力。可以使用以下命令安装它:
pip install Pillow
循序渐进的方法:
- 首先,我们必须导入模块。
Python3
# import required modules
import tkinter as tk
from tkinter import *
from PIL import Image
from PIL import ImageTk
Python3
# adjust window
root = tk.Tk()
root.geometry("200x200")
# loading the images
img = ImageTk.PhotoImage(Image.open("photo1.png"))
img2 = ImageTk.PhotoImage(Image.open("photo2.png"))
img3 = ImageTk.PhotoImage(Image.open("photo3.png"))
l = Label()
l.pack()
Python3
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x+1
root.after(2000, move)
# calling the function
move()
Python3
root.mainloop()
Python3
# import required modules
import tkinter as tk
from tkinter import *
from PIL import Image
from PIL import ImageTk
# adjust window
root=tk.Tk()
root.geometry("200x200")
# loading the images
img=ImageTk.PhotoImage(Image.open("photo1.png"))
img2=ImageTk.PhotoImage(Image.open("photo2.png"))
img3=ImageTk.PhotoImage(Image.open("photo3.png"))
l=Label()
l.pack()
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x+1
root.after(2000, move)
# calling the function
move()
root.mainloop()
- 加载图像。
蟒蛇3
# adjust window
root = tk.Tk()
root.geometry("200x200")
# loading the images
img = ImageTk.PhotoImage(Image.open("photo1.png"))
img2 = ImageTk.PhotoImage(Image.open("photo2.png"))
img3 = ImageTk.PhotoImage(Image.open("photo3.png"))
l = Label()
l.pack()
- 现在我们必须创建一个名为move的函数来使图像移动(这里的意思是一个图像出现,移动后它消失。
蟒蛇3
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x+1
root.after(2000, move)
# calling the function
move()
- 现在我们只需要调用 tkinter 的 mainloop函数来结束任务。
蟒蛇3
root.mainloop()
- 全码=
蟒蛇3
# import required modules
import tkinter as tk
from tkinter import *
from PIL import Image
from PIL import ImageTk
# adjust window
root=tk.Tk()
root.geometry("200x200")
# loading the images
img=ImageTk.PhotoImage(Image.open("photo1.png"))
img2=ImageTk.PhotoImage(Image.open("photo2.png"))
img3=ImageTk.PhotoImage(Image.open("photo3.png"))
l=Label()
l.pack()
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x+1
root.after(2000, move)
# calling the function
move()
root.mainloop()
输出: