首页 > 解决方案 > 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 日之前的任何内容都应该不相关)以查看它之前是如何工作的,但它肯定一直在工作,然后我很可能在提交之前破坏了它。

标签: pythontkinter

解决方案


这要感谢@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])

推荐阅读