您好,我正在制作一个带有图像和两个按钮的 tkinter 窗口,并使用这些按钮
previous
并next
在我单击按钮时在图像之间切换问题是我每次单击其中一个按钮时都不知道如何更改图像
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()