0

Hello, please i'm making a tkinter window with an image and two buttons, and using those buttons previous and next to switch between images whenever i click the buttons the problem is that i dont know how to change the image everytime i click one of the buttons

import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
import os

BASE_DIR = os.path.dirname(os.path.relpath(__file__))
image_dir = os.path.join(BASE_DIR, "my_training_face")

class MainUi(tk.Tk):
    def listDir(dir):
        global names
        global dict
        names = []
        dict = {}
        fileNames = os.listdir(dir)
        for fileName in fileNames:
            names.append(fileName)
        i = 0
        while i < len(names):
            dict[i] = (names[i])
            i = i + 1
        return dict

    listDir(image_dir)


    def get_name(self, cmpt):

        try:
            self.name = names[cmpt]
            return self.name
        except:
            return "Empty Case"

    def get_nbrHab(self):
        try:
            self.nbr = len(names)
            return self.nbr
        except:
            pass

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("300x400")
        self.geometry("+500+100")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)

        self.frames = {}

        self.frames = {}
        frame = StartPage(container, self)
        self.frames[StartPage] = frame
        frame.place(relx=0, rely=0, relwidth=1, relheight=1)




class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.configure(background='white')
        # self.master.configure(background='black')
        self.label = tk.Label(self, text=MainUi.get_name(self,0))
        self.label.pack(pady=10, padx=10)

        button1 = ttk.Button(self, text="Next", width=7, command = lambda: self.next_clicked())
        button1.place(relx=0.8, rely=0.9)
        button2 = ttk.Button(self, text="Back", width=7, command = lambda: self.back_clicked())
        button2.place(relx=0.1, rely=0.9)
        self.imgs = []
        self.resizing = []
        self.finals = []
        try:
            for i in range(MainUi.get_nbrHab(self)):
                self.imgs.append(Image.open(image_dir + "/" + MainUi.get_name(self, self.compteur) + "/1.jpg"))
                self.resizing.append(self.imgs[i].resize((160,120), Image.ANTIALIAS))
                self.finals.append(ImageTk.PhotoImage(self.resizing[i]))
        except:
            return

        self.label_img = tk.Label(self, bg='white', image= self.finals[0])
        self.label_img.image = self.finals[0]
        self.label_img.place(relx=0.21, rely=0.15)



 compteur = 0
        def next_clicked(self):
            self.label.config(text=MainUi.get_name(self,self.compteur))
            print(self.compteur)
            self.label_img.config(image=self.finals[self.compteur])
            self.label_img.image=self.finals[self.compteur]
            self.compteur += 1
    


 def back_clicked(self):
        self.compteur-=1

app = MainUi()
app.mainloop()
  • Here is what I suggest: Add all images' **path** to the list. Then when you click next, try doing: ```ImageTk.PhotoImage(file=str(self.list1[self.compteur))```. Here I have taken ```self.list1``` to add the images path, ```self.compteur=1```. Also, then add 1 to ```self.compteur - self.compteur```. Do the same while going backwards except subtract ```self.compteur - self.compteur-=1``` –  Jun 09 '21 at 02:22
  • can you please explain that more for me ? – mouad touhafi Jun 09 '21 at 18:58
  • Add the path of all the Images in a particular list, say ```self.lit1```. then define a number ```self.count=1```. When when you define an function for next button, you can fetch the second elements of the list like ```self.img=ImageTk.PhotoImage(file=self.lit1[self.count])``` and then use ```.config``` –  Jun 10 '21 at 01:03

3 Answers3

1

Here is the code. This is just for reference. This is root15.png, root14.png,rot13.png respectively.

enter image description here enter image description here

from tkinter import *

class ChangeImage:
    def __init__(self,root):
        self.root = root
        self.root.geometry("700x600")
        self.list1=[r"C:\Users\91996\Documents\Visual studio code\Visual Studio\rot13.png",r"C:\Users\91996\Documents\Visual studio code\Visual Studio\root15.png",r'C:\Users\91996\Documents\Visual studio code\Visual Studio\root14.png']
        self.compteur=0
        self.im=PhotoImage(file=self.list1[self.compteur])
        self.im_lbl=Label(self.root,image=self.im)
        self.im_lbl.pack()
        Button(self.root,text="Next Picture",command=self.next_picture).pack(pady=5)
        Button(self.root,text="Back Picture",command=self.back_picture).pack(pady=5)
    def next_picture(self):
        
        if self.compteur>=len(self.list1)-1:
            pass
        else:
            self.compteur+=1
            self.im=PhotoImage(file=self.list1[self.compteur])
            self.im_lbl.config(image=self.im)
    def back_picture(self):
        if self.compteur<=0:
            pass
        else:
            self.compteur-=1
            self.im=PhotoImage(file=self.list1[self.compteur])
            self.im_lbl.config(image=self.im)

root=Tk()
ob=ChangeImage(root)
root.mainloop()
0

I usually use .config() to update the widgets for example ->

from tkinter import *
root = Tk()
label = Label(root, text='This will be updated!')
btn = Button(root, text="Update It", command=lambda : label.config(text='Its Updated!'))
btn.pack()
root.mainloop()

Same thing can be done using Images and Other Widgets Like Buttons

0

There is issue in your code:

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        ...
        try:
            for i in range(MainUi.get_nbrHab(self)):
                # "self.compteur" is not yet defined here
                # also you should use "i" instead of "self.compteur"
                self.imgs.append(Image.open(image_dir + "/" + MainUi.get_name(self, self.compteur) + "/1.jpg"))  
        ...

So the correct code should be:

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        ...
        self.compteur = 0
        try:
            for i in range(MainUi.get_nbrHab(self)):
                self.imgs.append(Image.open(os.path.join(image_dir, MainUi.get_name(self, i), "1.jpg")))
        ...

Note that I don't know the last argument 1.jpg is correct or not, but it seems not required.

Then the functions for Back and Next buttons should be something like below:

def next_clicked(self):
    if self.compteur+1 < len(self.finals):
        self.compteur += 1
        self.label.config(text=MainUi.get_name(self, self.compteur))
        self.label_img.config(image=self.finals[self.compteur])
        #self.label_img.image=self.finals[self.compteur] # this line is not necessary actually

def back_clicked(self):
    if self.compteur > 0:
        self.compteur -= 1
        self.label.config(text=MainUi.get_name(self,self.compteur))
        self.label_img.config(image=self.finals[self.compteur])
acw1668
  • 40,144
  • 5
  • 22
  • 34