首页 > 解决方案 > 如何在 Tkinter 中动态创建没有特定类实例化的小部件?

问题描述

我正在尝试动态创建一定数量的小部件,然后能够修改它们。

例如,我需要一些 Checkboxes :

# Class level lists to store the CheckButtons and their values
self.checkbutton_list = []
self.checkbutton_values_list = []

# With self.amount_of_widgets an integer
for i in range(0, self.amount_of_widgets):
    # We create the value of the current CheckButton, default is 0
    self.checkbutton_values_list.append(IntVar())
    # We create the CheckButton and append it to our list
    self.checkbutton_list.append(Checkbutton(self.canvasR, 
                                     text="rtest : " + str(i),
                                     variable=self.checkbutton_values_list[i],
                                     onvalue=1,
                                     offvalue=0,
                                     height=1,
                                     width=10))
    # As there is a lot of CheckButtons, they have to be browsable inside the canvas 
    # named canvasR, which has a scrollbar. To browse the created CheckButtons in the 
    # canva, we need to use the create_window function :
    self.canvasR.create_window(x, y, window=self.comp_checkbutton_list[i])
    y = y + 100

这一代运行良好,我能够在所需位置创建所有所需的小部件,并将它们存储到专用列表中。例如,我做了类似的事情来创建空白图像(我想稍后更新这些图像):

for i in range(0, self.amount_of_widgets):
    # With default photo a PhotoImage object stored at class level
    self.photo_list.append(self.default_photo)
    self.photo_area_list.append(self.canvasR.create_image(x, y, 
                                     image=self.photo_list[i], 
                                     anchor=NW))
    y = y + 100

问题是我无法更新创建的小部件,如果我尝试.itemconfig()在以下代码中调用,我会得到一个 _tkinter.TclError: invalid boolean operator in tag search expression

for i in range(0, self.max_image_displayed):
    self.canvasR.itemconfig(self.checkbutton_list[i], fill='black', text='')

我知道它可能不起作用,因为每个小部件并不是专门针对主类存在的,因为它们没有在类中显式创建。此范围内仅存在存储它们的列表。

但我不会在我的代码中一一声明数千个 CheckBoxes 或 Images 字段,例如:

self.area1 = self.canvasR.create_image(0, 0, image=self.photoimage1, anchor=NW)
self.area_list.append(self.area1)
self.area2 = self.canvasR.create_image(0, 100, image=self.photoimage2, anchor=NW)
self.area_list.append(self.area2)
# ...
self.area9999 = self.canvasR.create_image(0, 0, image=self.photoimage999, anchor=NW)
self.area_list.append(self.area9999)

我能做什么?

标签: pythontkinter

解决方案


问题是我无法更新创建的小部件,如果我尝试像下面的代码一样调用 .itemconfig(),我得到一个 _tkinter.TclError: invalid boolean operator in tag search expression

当您调用self.canvasR.itemconfig时,第一个参数需要是画布上单个项目的标识符或标签。但是,您传入的self.defaultPhoto绝对不是项目标识符或标签。

换句话说,如果您的目标itemconfigself.canvasR.create_image(...)修改由create_image.


推荐阅读