Quantcast
Channel: User martineau - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by martineau for How to stop/pause and restart the code using same button? (tkinter)

$
0
0

Here's runnable code that illustrates how to do it. It uses several global variables to keep track of the current state of the slide show that the various functions use to determine what needs to be be done.

It simplies the logic you had for determining the next image to display by adding one to then current image index and the applying the modulo % the number of images in show which forces the index back to 0 whenever it exceeds the number of image that there are — which can all be done with a single statement: cur_img = (cur_img+1) % len(slides).

You could get rid of the most of the globals by defining a SlideShowclass that encapsulated the state variables and defined the related functions that manipulate them.

from pathlib import Pathfrom PIL import Imagefrom PIL import ImageTkimport tkinter as tkroot = tk.Tk()root.geometry("500x500")after_id = Nonecur_img = 0paused = Trueimage_folder = Path('./photos')slides = [ImageTk.PhotoImage(Image.open(filename))            for filename in image_folder.glob('*.png')]def slide_show():"""Change to next image (wraps around)."""    global after_id, cur_img, paused    if not paused:        cur_img = (cur_img+1) % len(slides)        lbl.config(image=slides[cur_img])    after_id = root.after(2000, slide_show)def start():    global after_id, cur_img, paused    paused = False    if after_id:  # Already started?        root.after_cancel(after_id)        after_id = None    slide_show()def pause():    global after_id, cur_img, paused    paused = Truelbl = tk.Label(image=slides[cur_img])lbl.pack()btn_1 = tk.Button(root, text="start", command=start)btn_1.pack()btn_2 = tk.Button(root, text="pause", command=pause)btn_2.pack()root.mainloop()

Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>