python - 如何在 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)
我能做什么?
解决方案
问题是我无法更新创建的小部件,如果我尝试像下面的代码一样调用 .itemconfig(),我得到一个 _tkinter.TclError: invalid boolean operator in tag search expression
当您调用self.canvasR.itemconfig
时,第一个参数需要是画布上单个项目的标识符或标签。但是,您传入的self.defaultPhoto
绝对不是项目标识符或标签。
换句话说,如果您的目标itemconfig
是self.canvasR.create_image(...)
修改由create_image
.
推荐阅读
- r - 在 R Shiny 中,如何使用条件 if/then 代替“req”或必需的输入函数来响应操作按钮?
- python-3.x - argparse '参数 1 必须是 str、bytes 或 bytearray,而不是 None'
- image-processing - 计算电池阳极的层数
- vue.js - VuetifyJS `nuxt` 属性不像 NuxtJS 框架中的 `nuxt-link` 那样工作
- python - DialogFlow 发送 API 请求但未接收数据
- python - 无法在类内的列表中执行函数
- python - 使用命令行直接向 Python 端口扫描器添加参数
- android - 如何在 Android 中的 string.xml 文件中指示缺少翻译
- java - java版本“1.8.0_211”的详细信息是什么意思?
- syntax - 如何理解伊莎贝尔的语法和翻译