python - 如何在python中不断使用Tkinter一张一张地滑动图像?
问题描述
我正在用 Python 学习 Tkinter。我正在尝试在没有按钮的情况下不断地一张一张地制作图像的幻灯片更换器。图像将在延迟一段时间后自动更改。我正在使用 for 循环从我的目录中迭代我的图像文件,但是当我在目录中只提供一个图像时,图像会在 tkinter 弹出显示上闪烁,但是当我提供多个图像时,我的图像是'没有出现在显示屏上。
import os
from tkinter import *
from PIL import Image,ImageTk
import time
path = "Album"
root = Tk()
root.geometry("576x432")
location = os.listdir("Album")
print(location)
#Output: ['1 (1).jpg', '1 (2).jpg', '1 (3).jpg', '1 (4).jpg', '1 (5).jpg', 'not out.png', 'out.png', 'pending.png']
for iteam in location:
image1 = Image.open(f"Album/{iteam}")
photo1 = ImageTk.PhotoImage(image1)
photo_label1 = Label(image=photo1)
photo_label1.pack()
time.sleep(2)
root.mainloop()
有没有办法做到这一点?
解决方案
正如我之前所说,我在这里收集了代码,以在每 2 秒(2000 毫秒)后重复显示图像。我已经最大限度地评论了下面的代码,以便在旅途中更容易理解。
from tkinter import *
from PIL import Image, ImageTk
import time
from glob import glob
from tkinter import filedialog
root = Tk()
root.geometry("576x432")
path = filedialog.askdirectory(title='Choose the directory with images') #get the directory path
location1 = glob(f'{path}//*.png') #get the path of all png image
location2 = glob(f'{path}//*.jpg') #get the path of all jpg image
final_loc = location1 + location2 #combine those list to a final main list
print(final_loc) #check the list
#Output: ['1 (1).jpg', '1 (2).jpg', '1 (3).jpg', '1 (4).jpg', '1 (5).jpg', 'not out.png', 'out.png', 'pending.png']
i = 0 #set the index value to 0
def show():
global i #so that the value of i changes on global scope
try:
image1 = Image.open(final_loc[i]) #open the index-th image
photo1 = ImageTk.PhotoImage(image1)
photo_label1.config(image=photo1) #using config so the image doesnt overlap
photo_label1.img = photo1 #keeping a reference
i += 1 #increasing the index number
except IndexError: #if no more items in the list to index
i = 0 #set index back to 0
finally:
root.after(2000,show) #keep repeating the function every 2 sec or 2000 ms
photo_label1 = Label(root) #create a label, later to be editeed
photo_label1.pack()
show() #call the function
root.mainloop()
我已经使示例尽可能动态。您可以选择目录,我更改os
为glob
,我相信这对这种情况有好处。您可以更进一步并添加另一个按钮来停止“幻灯片放映”。
与 tkinter一起使用并不好,sleep()
因为它会在等待时冻结您的 GUI。所以改为使用 tkinter 方法after(ms,func)
。
after()
方法主要有两个参数:
ms
- 函数应该运行的时间,以毫秒(ms)为单位func
- 在给定 ms 完成后运行的函数。
虽然更大的图像可能不适合您的屏幕,但这是一个全新的 Q,无论如何我已经在这里问过类似的Q。
推荐阅读
- multithreading - Rust 多线程异步 Websocket 服务器
- c# - 如何在两个节点之间添加新节点以及附加到新节点的所有子节点
- hibernate-search - 休眠搜索中的重叠日期结果
- python-3.x - Python 3.7 不导入另一个 python 文件
- reactjs - 如何在反应中将功能传递到功能组件中的另一个状态
- c# - 如何在派生控制器中模拟 HttpContext.RequestServices.GetService<> 注入的服务?
- python - 任务算法
- sql - 如何找到两个值不同且其中一个可以为 NULL 的行?为什么 NULL != 1 是假的?
- tensorboard - TensorBoard 上只有黑色图像
- google-sheets - 将具有开始和结束日期的单个记录转换为 Google 表格中的多个记录?