PIL / tkinter - 使用按钮图像更新标签图像

时间:2014-01-13 20:35:05

标签: python tkinter python-imaging-library

我正在尝试实现我的简单图像查看器,其中我有一个主要标签和menubutton有三个选择。每个按钮都会创建不同数量的按钮,里面有图片。我想创建一个主标签,然后用按钮上的图像更新其图像。因此,当我单击带图像的第一个按钮时,该图像将出现在标签上,然后单击第二个按钮,将出现第二个图像,依此类推。我试图创建两个函数,一个用于创建标签并更新其图像,另一个用于获取按钮上的当前图像,但我无法正确执行第二个。感谢您的帮助。这是代码:

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk 

from functools import partial
from PIL import Image, ImageTk

class Halabala():
    def __init__(self):
        self.master = tk.Tk()
        self.master.geometry("1100x700")
        self.pictures = ["pavuk1.gif", "pavuk2.gif", "pavuk3.gif"]
        self.pictures2 = ["cukor1.gif", "cukor2.gif", "cukor3.gif", "cukor4.gif", "cukor5.gif"]

        self.lists_images = []
        self.lists_images2 = []

        self.init_image_list()

        self.lists_labels = []

        #self.main_label = tk.Label(self.master, image = None).grid(row = 0, column = 0) 
        #image with original size 

        self.rbutton = tk.Menubutton(self.master, text = "Choose picture")
        self.picks2 = tk.Menu(self.rbutton)
        self.rbutton.config(menu=self.picks2)
        self.picks2.add_command(label = "Spider", command = partial(self.create_labels,3))
        self.picks2.add_command(label = "Sugar", command = partial(self.create_labels,5))
        self.rbutton.config(width = 30, bg = "white", bd = 5, relief = tk.RAISED)
        self.rbutton.place(x = 900, y = 30)
        self.master.mainloop()

    def init_image_list(self):
        for i in self.pictures:
                picture = Image.open(i)
                picture.thumbnail((130, 130))
                self.lists_images.append(ImageTk.PhotoImage(picture))

        for i in self.pictures2:
                picture = Image.open(i)
                picture.thumbnail((130, 130))
                self.lists_images2.append(ImageTk.PhotoImage(picture))


    def create_labels(self, num):

        for label in self.lists_labels:
            label.destroy()
        self.lists_labels=[]

        for i in range(num):
            if num == 3:
                but = tk.Button(self.master, image = self.lists_images[i]) #command = self.get_command
                but.grid(row = 2, column = i + 1) #label will be in the first row
                self.lists_labels.append(but)
            else:
                but = tk.Button(self.master, image = self.lists_images2[i])
                but.grid(row = 2, column = i + 1)
                self.lists_labels.append(but)

    #def get_command(self):
        #self.main_label = tk.Label(self.master, image = self.get_image).grid(row = 0, column = 0)

    #def get_image(self):
    # don't know how to get current image from button

myapp = Halabala()

0 个答案:

没有答案