python - 如何创建带有图像和文本的复选按钮?

标签 python python-3.x image tkinter checkbox

我刚刚开始使用tkinter小部件并正在尝试创建 Checkbuttons带有图像和文本标签。不幸的是,这不能用基本的 Checkbutton(master=, image=, text=) 来完成。设置image抑制text .

这是一个愚蠢但可重现的示例,说明了我正在尝试做的事情。

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

def getImgFromUrl(url): # using solution from : https://stackoverflow.com/a/18369957/2573061
   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://icons.iconarchive.com/icons/martin-berube/flat-animal/64/dachshund-icon.png',
             'http://icons.iconarchive.com/icons/iconka/meow/64/cat-walk-icon.png',
             'http://icons.iconarchive.com/icons/sonya/swarm/64/Unicorn-icon.png']

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

给我:

enter image description here

但我希望在图像下方或侧面添加“猫”、“狗”和“ unicorn ”标签。

同样重要的是,该解决方案适用于任意数量的 Checkbuttons ,如 for 中所示上面循环。

我应该使用网格并堆叠这些Checkbuttons旁边Labels ?到目前为止我已经设法避免学习它。或者用 Pack 很容易做到吗? ?

最佳答案

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

按照 Bryan's comment 中的建议,这可以通过配置 Checkbuttoncompound 选项来完成。

简单地替换:

cb = Checkbutton(root, text=labels[i], image = images[i])

与:

cb = Checkbutton(root, text=labels[i], image = images[i], compound='left')

或设置compound option['bottom', 'center', 'left', 'right', 'top']元素,默认为 None:

cb['compound'] = 'top'
<小时/>

下面的示例为大多数 Windows 用户提供了一个示例:

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()

mypath = r"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"
img = Image.open(mypath)
glb_img = ImageTk.PhotoImage(img)
tk.Checkbutton(root, text="Koala", image=glb_img, compound='top').pack()

root.mainloop()
<小时/>

还值得注意的是,导入 PIL 对于 .png 格式来说是多余的,可以使用 tk.PhotoImage(data=image_data)tk.PhotoImage(file=image_file)

关于python - 如何创建带有图像和文本的复选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48085771/

相关文章:

python 将字典数组映射到字典?

image - 使用opencv仅去除图像中的黑点

css - React Native - 图像半圆(使用 CSS)

python - Maya python 地形生成器

python : putting functions into classes

python - 如何使客户端套接字以非阻塞方式从另一个套接字接收数据?

image - 如何将 BufferedImage 转换为图像以在 JSP 上显示

python - 找出所有满足 i+j+k=n 的三元组 i,j,k

python - Tkinter - 在使用任何小部件之前最大化和最小化窗口,在我使用它们时隐藏小部件

python-3.x - Visual Studio Code、Conda 和 Python 环境(我无法让它工作)