jeudi 4 janvier 2018

How to create Checkbuttons with labeled images?

I am just getting started with tkinter widgets and am trying to create Checkbuttons with both images and text labels. Unfortunately, this cannot be done with basic Checkbutton(..., image= , text= ) as setting the image suppresses the text.

Here's a silly yet reproducible example of what I'm trying to do.

from tkinter import Tk, Frame, Checkbutton, Label
from PIL import ImageTk, Image
import requests

def getImgFromUrl(url): # using solution from : http://ift.tt/2CUNif1
   try:
       r = requests.get(url, stream=True)
       pilImage = Image.open(r.raw)
       phoImage = ImageTk.PhotoImage(pilImage)
       return phoImage
   except Exception as e:
       print('Error ' + repr(e) )
       return None


class AnimalPicker(Frame):
    def __init__(self):
        super().__init__()
        self.initUI()        

    def initUI(self):
        self.master.title("Animal Picker")


def main(): 
    root = Tk()
    root.geometry("250x450+300+300")
    app = AnimalPicker()

    imageUrls = ['http://ift.tt/2CnFEbV',
             'http://ift.tt/2CSm34Y',
             'http://ift.tt/2Cqr5Vh']

    labels = ['Dog','Cat','Unicorn']

    images = [getImgFromUrl(x) for x in imageUrls]

    for i in range(len(images)):
        cb = Checkbutton(root, text=labels[i], image = images[i])
        cb.pack(anchor = 'w', padx=5,pady=5) 
    root.mainloop()  

if __name__ == '__main__':
    main()   

Gives us:

enter image description here

But I would like to have the labels ("Cat", "Dog", "Unicorn") either underneath or to the side of the images.

It's also important that the solution work for an arbitrary number of Checkbuttons, as in the for loop above.

Should I be using Grid and stacking these Checkbuttons next to Labels? I've managed to avoid learning it so far. Or is it easy to do with Pack?




Aucun commentaire:

Enregistrer un commentaire