0

您好,我正在制作一个带有图像和两个按钮的 tkinter 窗口,并使用这些按钮previousnext在我单击按钮时在图像之间切换问题是我每次单击其中一个按钮时都不知道如何更改图像

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()
4

3 回答 3

0

我通常.config()用来更新小部件,例如 ->

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()

使用图像和其他小部件(如按钮)可以完成相同的操作

于 2021-06-09T02:38:46.170 回答
0

您的代码存在问题:

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"))  
        ...

所以正确的代码应该是:

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")))
        ...

请注意,我不知道最后一个参数1.jpg是否正确,但似乎不需要。

那么BackNext按钮的功能应该如下所示:

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])
于 2021-06-09T02:46:28.487 回答
0

这是代码。这仅供参考。这分别是root15.png, 。root14.pngrot13.png

在此处输入图像描述 在此处输入图像描述

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()
于 2021-06-10T02:07:03.200 回答