python - Tkinter:使用图像配置多个按钮
问题描述
我有一个函数,它采用图像文件的名称并使用属性创建它们的网格作为按钮image
,这就是问题出现的地方,因为我需要按钮对象来创建图像,因为我的另一个功能fit_image()
(在这个case 完全适合对象内部的图像,因此full=True
)。在不将图像添加到这些按钮的情况下运行它的结果很好,并且所有按钮都是可点击的:
self.image_buttons = {}
count = 0
# goes by column
for y in range(height_divisor):
# row
for x in range(width_divisor):
self.image_buttons[count] = tk.Button(self.preview_frame)
self.image_buttons[count].place(
relx=0 + (1 / width_divisor * x),
rely=0 + (1 / height_divisor * y),
relwidth=1 / width_divisor,
relheight=1 / height_divisor,
anchor="nw",
)
# self.current_image = fit_image(
# Image.open(names_of_files[count]), self.image_buttons[count], full=True
# )
# self.image_buttons[count].configure(image=self.current_image)
count += 1
print(self.image_buttons)
打印语句的结果:
{0: <tkinter.Button object .!toplevel2.!frame2.!button>, 1: <tkinter.Button object .!toplevel2.!frame2.!button2>, 2: <tkinter.Button object .!toplevel2.!frame2.!button3>, 3: <tkinter.Button object .!toplevel2.!frame2.!button4>}
但是,一旦我取消注释此代码,只有最后一个按钮是可点击的并且上面确实有图像,但所有其他按钮都是空白且不可点击的按钮。之后我尝试将注释(图像配置)行放在单独的 for 循环中,以通过并配置每个按钮无济于事。虽然我以前做过这项工作,甚至尝试梳理我的 repo的提交(8 月 8 日之前的任何内容都应该不相关)以查看它之前是如何工作的,但它肯定一直在工作,然后我很可能在提交之前破坏了它。
解决方案
这要感谢@jasonharper 的评论,通过更改这两行并添加新字典来解决:
self.image_buttons, self.images = {}, {}
#for loops here
self.images[count] = fit_image(
Image.open(names_of_files[count]), self.image_buttons[count], full=True
)
self.image_buttons[count].configure(image=self.images[count])
推荐阅读
- android - CSS注入完成后如何在webview中显示网站?
- c# - 使用 C# 删除文档列中 Word 表格上方的段落
- ionic4 - 离子如何从数组数据中成像
- python - 基于第三列的 Pandas 数据框颜色的 Seaborn 散点图
- python - 有没有办法从 Python 中的字符串中查找和删除标点符号?
- laravel - 搜索关系数据 laravel scout elasticsearch
- sql - 如何更改表以添加引用同一表的主键的外键约束
- arraylist - Kotlin ArrayList 不会使用“添加”方法附加对象
- javascript - 为什么 JavaScript 有默认导出?
- django - 我是 Django 的新手。如何解决 csrf 令牌丢失或不正确的错误?我在视图中使用了渲染请求