【发布时间】:2020-05-10 02:40:29
【问题描述】:
我有一个用于图像幻灯片放映的简单 Tkinter 应用程序。
我使用.after(100, rotate_image)每 100 毫秒更新与标签关联的图像。
定义updater() 是为了在窗口打开时将其作为无限循环运行。
由于某种原因,图像只更新一次。它不会循环到列表中的第 2 项或更高项。
我的意图是在1->2->3->1->2->3....中旋转图像
类似地,一个按钮与相同的功能相关联rotate_image
该按钮可以正常工作并在图像列表中旋转。
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
window = tk.Tk()
window.title("Image scroll")
window.geometry("800x600")
window.minsize(300, 300)
#load image, resize & place text
wx= 150
hx = 150
images =[ 'beach.jpg', 'DSC325.jpg','DSC323.jpg']
val=0
def load_img(img_name):
global photo1 # alternative fix for photoimage garbage colelction issue
img = Image.open(img_name)
img = img.resize((wx,hx), Image.ANTIALIAS)
photo1= ImageTk.PhotoImage(img)
return photo1
def rotate_image(event=None):
global val
# simple Rotation function to loop images `1->2->3->1->2->3.`
if val== len(images)-1:
val=0
else:
val +=1 # select next
img2= load_img(images[val])
img_panel.configure(image=img2)
img_panel.image = img2
def updater():
count=1
while count<=100:
window.after(100, rotate_image)
count+=1
#define main layout frames
frm_LEFT_outer = tk.Frame(master=window, width = 600,bg= '#beb7e2', relief=tk.GROOVE, borderwidth=2)
frm_LEFT = tk.Frame(master=frm_LEFT_outer, bg= '#beb7e2', relief=tk.GROOVE, borderwidth=2)
frm_LEFT_outer.pack(side =tk.LEFT, fill=tk.BOTH, expand=True )
frm_LEFT.pack(expand=True, )
img_panel = tk.Label(master=frm_LEFT, image=load_img(images[val]))
img_panel.pack(expand=True)
btn_next = ttk.Button(master=frm_LEFT, text="NEXT", width=8, command=rotate_image)
btn_next.pack(expand=False)
updater() # auto loop through images while the window is open
window.mainloop()
【问题讨论】:
-
你连续调用了一百次
.after(),所以 0.1 秒后你很快接到了一百次调用rotate_image()。需要一次调用.after()一次,然后在延迟函数中再次调用。