在Python中创建简单的图库,Tkinter& PIL

时间:2013-07-06 15:54:36

标签: python user-interface tkinter python-imaging-library

所以,我正在使用python制作图库的在线课程的简单项目。问题是创建3个按钮,一个是Next,Previous和Quit。到目前为止,退出按钮工作,下一个加载一个新的图像,但在不同的窗口,我对Tkinter的python和GUI编程很新,所以这是初学者课程的一个重要部分。

到目前为止,我的代码看起来像这样,一切正常。但是我需要帮助才能创建上一个和下一个按钮,到目前为止我已经使用了新语句,但它在另一个窗口中打开。我只是想显示1张图片,然后用一些简单的文字点击下一张图片。

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

2 个答案:

答案 0 :(得分:1)

通过设置图像项目来更改图像: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()

答案 1 :(得分:-1)

我的用户界面不太好。但我的逻辑运行良好,我测试得很好。你可以改变用户界面。它是如何工作的,首先我们需要浏览文件,当我们点击打开它时,它会显示图像,并且它还会创建一个位于所选图像文件夹中的图像列表。我只提到了“.png”和“.jpg”文件。如果你想添加更多你可以在path_func()中添加它。

from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
import os

class ImageViewer:

    def __init__(self, root):
        
        self.root = root
        self.root.title("Photo Viewer")
        self.root.geometry("1360x750")
        self.root.config(bg = "lightblue")

        menus = Menu(self.root)
        self.root.config(menu = menus)

        file_menu = Menu(menus)
        menus.add_cascade(label = "File", menu = file_menu)
        
        file_menu.add_command(label = "Open", command = self.open_dialog)
        file_menu.add_separator()
        file_menu.add_command(label = "Previous", command = self.previous_img)
        file_menu.add_command(label = "Next", command = self.next_img)
        file_menu.add_separator()
        file_menu.add_command(label = "Exit", command = self.root.destroy)

        self.label = Label(self.root, text = "Open a image using open menu", font = ("Helvetica", 15), foreground = "#0000FF", background = "lightblue")
        self.label.grid(row = 0, column = 0, columnspan = 4)

        self.buttons()

    def path_func(self, path):
        l = []
        self.path = path.split('/')
        self.path.pop()

        self.path = '/'.join([str(x) for x in self.path])
        
        #print(self.path)
        
        for file in os.listdir(self.path):
            if file.endswith('.jpg') or file.endswith('.png'):
                l.append(file)
                #print(l)

        def join(file):
            os.chdir(self.path)
            #print(os.getcwd())
            cwd = os.getcwd().replace('\\', '/')
            #print(cwd)
            f = cwd + '/' + file
            #print(f)
            return f
        
        global file_list
        file_list = list(map(join, l))
        #print(file_list) 

    def open_dialog(self):
            global file_name
            file_name = filedialog.askopenfilename(initialdir = "C:/Users/elcot/Pictures", title = "Open file")
            #print(file_name)
            self.view_image(file_name)
            self.path_func(file_name)

            '''except:
            label = Label(self.root, text = "Select a file to open")
            label.grid(row = 4, column =1)'''

    def view_image(self, filename):
        try:
            self.label.destroy()
            global img
            img = Image.open(filename)
            img = img.resize((1360, 650))
            img = ImageTk.PhotoImage(img)
        
        #print(img)

            show_pic = Label(self.root, image = img)
            show_pic.grid(row = 1, column = 0, columnspan = 3)

        except:
            pass
        
    def buttons(self):
        open_button = Button(self.root, text = "Browse", command = self.open_dialog, background = "lightblue")
        open_button.grid(row = 1, column = 1)
        
        previous_button = Button(self.root, text = "Previous", command = self.previous_img, background = "lightblue", width = 25)
        previous_button.grid(row = 3, column = 0, pady = 10)

        empty = Label(self.root, text = "        ", background = "lightblue")
        empty.grid(row = 3, column = 1)
        
        next_button = Button(self.root, text = "Next", command = self.next_img, background = "lightblue", width = 25)
        next_button.grid(row = 3, column = 2)


    def previous_img(self):
        global file_name
        #print(file_list)
        index = file_list.index(file_name)
        #print(index)
        curr = file_list[index - 1]
        #print(curr)
        self.view_image(curr)
        file_name = curr


    def next_img(self):
        global file_name
        index = file_list.index(file_name)
        #print(index)
        if index == len(file_list) - 1:
            index = -1
            curr = file_list[index + 1]
            #print(curr)
            self.view_image(curr)
            file_name = curr
        else:
            curr = file_list[index + 1]
            #print(curr)
            self.view_image(curr)
            file_name = curr

 
if __name__ == "__main__":
    root = Tk()
    gallery = ImageViewer(root)
    root.mainloop()