我刚刚开始使用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()
给我:
但我希望在图像下方或侧面添加“猫”、“狗”和“ 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 中的建议,这可以通过配置 Checkbutton
的 compound
选项来完成。
简单地替换:
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/