gpt4 book ai didi

python - tkinter:在按钮中实现幻灯片功能?

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:50 25 4
gpt4 key购买 nike

我现在正在制作一个 tkinter gui 程序我想显示幻灯片 - def slip,当我单击 def GUI_PART 中的按钮 - boldbutton 时,但在我的代码中,幻灯片不是'不工作。

请帮忙。

class mainapp(): 
def slide(self):
root1=Tk()
self.root1.geometry("+{}+{}".format(70, 100))
title("a simple Tkinter slide show")
# delay in seconds (time each slide shows)
delay = 2.5
imageFiles=glob.glob('/home/imagefolder/*.png')
photos = [PhotoImage(file=fname) for fname in imageFiles]
button = Button(root1,command=root1.destroy)
button.pack(padx=5, pady=5)
for photo in photos:
button["image"] = photo
root1.update()
time.sleep(delay)

def GUI_PART(self, Master):
self.master = Master
Master.title("Start")
self.masterFrame = Frame(self.master)
self.masterFrame.pack()
...
self.boldbutton = Button(self.tool3_frame, text="Slide show",command=self.slide)
self.boldbutton.pack(side=LEFT)

最佳答案

GUI 工具包是事件驱动的,Tkinter 也不异常(exception)。

这意味着程序在mainloop()中运行,并且不能使用带 sleep 的循环来显示图像。

您应该做的是将图像路径列表保存在应用程序对象中,并使用 after() 方法。此外,我将使应用程序类继承自 Tk。

示例(Python 3,在 Python2 中使用 Tkinter 而不是 tkinter):

import glob
import tkinter as tk
from PIL import Image, ImageTk


class ImageViewer(tk.Tk):

def __init__(self):
"""Create the ImageViewer."""
# You can press q to quit the program.
self.bind_all('q', self.do_exit)
# Attributes for the image handling.
self.image_names=glob.glob('/home/imagefolder/*.png')
self.index = 0
self.photo = None
# We'll use a Label to display the images.
self.label = tk.Label(self)
self.label.pack(padx=5, pady=5)
# Delay should be in ms.
self.delay = 1000*2.5
# Display the first image.
self.show_image()

def show_image(self):
"""Display an image."""
# We need to use PIL.Image to open png files, since
# tkinter's PhotoImage only reads gif and pgm/ppm files.
image = Image.open(self.image_names[index])
# We need to keep a reference to the image!
self.photo = ImageTk.PhotoImage(image)
self.index += 1
if self.index == len(self.image_names):
self.index = 0
# Set the image
self.label['image'] = self.photo
# Tell tkinter we want this method to be called again after a delay.
self.after(self.delay, self.show_image)

def do_exit(self, event):
"""
Callback to handle quitting.

This is necessary since the quit method does not take arguments.
"""
self.quit()

root = ImageViewer()
root.mainloop()

关于python - tkinter:在按钮中实现幻灯片功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44481059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com