Skip to main content
 首页 » 编程设计

python之在 Python、Tkinter 和 PIL 中创建简单的图片库

2025年05月04日9telwanggs

所以,我正在进行一个简单的在线类(class)项目,使用 Python 制作图片库。关键是要创建 3 个按钮,一个是 Next、Previous 和 Quit。到目前为止,退出按钮有效,下一个加载新图像但在不同的窗口中,我对使用 Tkinter 进行 python 和 GUI 编程还很陌生,所以这是初学者类(class)的重要部分。

到目前为止,我的代码看起来像这样并且一切正常。但是我需要有关如何制作上一个和下一个按钮的帮助,到目前为止我已经使用了 NEW 语句,但它会在不同的窗口中打开。我只想显示一张图片,然后单击下一张带有一些简单文本的图片。

import Image 
import ImageTk 
import Tkinter 
 
root = Tkinter.Tk(); 
text = Tkinter.Text(root, width=50, height=15); 
myImage = ImageTk.PhotoImage(file='nesta.png'); 
 
def new(): 
wind = Tkinter.Toplevel() 
wind.geometry('600x600') 
imageFile2 = Image.open("signori.png") 
image2 = ImageTk.PhotoImage(imageFile2) 
panel2 = Tkinter.Label(wind , image=image2) 
panel2.place(relx=0.0, rely=0.0) 
wind.mainloop() 
 
master = Tkinter.Tk() 
master.geometry('600x600') 
 
B = Tkinter.Button(master, text = 'Previous picture', command = new).pack() 
 
B = Tkinter.Button(master, text = 'Quit', command = quit).pack() 
 
B = Tkinter.Button(master, text = 'Next picture', command = new).pack() 
 
master.mainloop() 

请您参考如下方法:

通过设置图像项更改图像:Label['image'] = photoimage_obj

import Image 
import ImageTk 
import Tkinter 
 
image_list = ['1.jpg', '2.jpg', '5.jpg'] 
text_list = ['apple', 'bird', 'cat'] 
current = 0 
 
def move(delta): 
    global current, image_list 
    if not (0 <= current + delta < len(image_list)): 
        tkMessageBox.showinfo('End', 'No more image.') 
        return 
    current += delta 
    image = Image.open(image_list[current]) 
    photo = ImageTk.PhotoImage(image) 
    label['text'] = text_list[current] 
    label['image'] = photo 
    label.photo = photo 
 
 
root = Tkinter.Tk() 
 
label = Tkinter.Label(root, compound=Tkinter.TOP) 
label.pack() 
 
frame = Tkinter.Frame(root) 
frame.pack() 
 
Tkinter.Button(frame, text='Previous picture', command=lambda: move(-1)).pack(side=Tkinter.LEFT) 
Tkinter.Button(frame, text='Next picture', command=lambda: move(+1)).pack(side=Tkinter.LEFT) 
Tkinter.Button(frame, text='Quit', command=root.quit).pack(side=Tkinter.LEFT) 
 
move(0) 
 
root.mainloop()