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

时间:2017-06-11 06:36:35

标签: python tkinter slideshow

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

请帮忙。

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) 

1 个答案:

答案 0 :(得分:0)

GUI-toolkits是事件驱动的,而Tkinter也不例外。

这意味着该程序在mainloop()中运行,您无法使用带睡眠的循环来显示图像。

您应该做的是在应用程序对象中保存图像路径列表,并使用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()