I need the images to change if the cursor is inside the window without moving, but I managed to make the image changes only if the cursor is moving inside the window, how can I change the code?
JavaScript
x
17
17
1
from itertools import cycle
2
import tkinter as tk
3
from PIL import ImageTk, Image
4
import glob
5
6
image_files = glob.glob("*.jpg")
7
root = tk.Toplevel()
8
root.geometry("1600x900")
9
pictures = cycle((ImageTk.PhotoImage(file=image), image) for image in image_files)
10
picture_display = tk.Label(root)
11
picture_display.pack()
12
def show_slides(event):
13
img_object, img_name = next(pictures)
14
root.after(500, picture_display.config(image=img_object))
15
root.bind("<Motion>", show_slides)
16
root.mainloop()
17
Advertisement
Answer
You can calculate cursor position in loop and show image if it’s located within tkinter window:
JavaScript
1
26
26
1
import glob
2
import tkinter as tk
3
from PIL import ImageTk
4
from itertools import cycle
5
6
class App(object):
7
def __init__(self):
8
self.root = tk.Tk()
9
self.root.geometry('900x600')
10
self.lbl = tk.Label(self.root)
11
self.lbl.pack()
12
files = glob.glob('*.jpg')
13
self.images = cycle((ImageTk.PhotoImage(file=f), f) for f in files)
14
self.show()
15
self.root.mainloop()
16
17
def show(self):
18
abs_coord_x = self.root.winfo_pointerx() - self.root.winfo_rootx()
19
abs_coord_y = self.root.winfo_pointery() - self.root.winfo_rooty()
20
if 0 <= abs_coord_x <= self.root.winfo_width() and 0 <= abs_coord_y <= self.root.winfo_height():
21
img_object, img_name = next(self.images)
22
self.lbl.config(image=img_object)
23
self.root.after(1000, self.show)
24
25
App()
26