我目前在我的python gui中使用了一个Spinbox,它是通过使用Tkinter实现的。设置Spinbox的方法就是这个:
def _select_event(self, type, id):
""" Selects an event for editing its properties """
print("_select_event")
if not self._can_draw(): return
if type != self.event_type:
#Destroy all widgets on the frame and build those neccessary
for widget in self.event_edit_widgets: widget.grid_remove()
self.event_edit_widgets = []
self.event_type = type
if self.event_type == "Person": #Build widgets for person
if len(self.map.persons) <= id: return
print("mark0")
self.event_edit_widget_id_spinbox = tkinter.Spinbox(self.event_edit_widget, from_=0, to=len(self.map.persons) - 1, command=self._select_event(self.event_type, self.event_edit_type_dropdown.get()))
print("mark1")
elif self.event_type == "Warp": #Build widgets for warp
if len(self.map.warps) <= id: return
self.event_edit_widget_id_spinbox = tkinter.Spinbox(self.event_edit_widget, from_=0, to=len(self.map.warps) - 1, command=self._select_event(self.event_type, self.event_edit_type_dropdown.get()))
elif self.event_type == "Trigger": #Build widgets for trigger
if len(self.map.triggers) <= id: return
self.event_edit_widget_id_spinbox = tkinter.Spinbox(self.event_edit_widget, from_=0, to=len(self.map.triggers) - 1, command=self._select_event(self.event_type, self.event_edit_type_dropdown.get()))
elif self.event_type == "Sign": #Build widgets for sign
if len(self.map.signposts) <= id: return
self.event_edit_widget_id_spinbox = tkinter.Spinbox(self.event_edit_widget, from_=0, to=len(self.map.signposts) - 1, command=self._select_event(self.event_type, self.event_edit_type_dropdown.get()))
else:
raise Exception("Unkown event type selected: " + self.event_type)
#Push all common widgets to the ui
self.event_edit_widget_id_spinbox.grid(row=1, column=0, sticky=tkinter.NW)
self.event_edit_widget_id_spinbox.config(state="readonly")
self.event_edit_widgets.append(self.event_edit_widget_id_spinbox)
#Update all widgets
self.event_edit_widget_id_spinbox.delete(0, tkinter.END)
self.event_edit_widget_id_spinbox.insert(0, str(id))
正如您可以看到为例如设置的Spinbox self.event_type ==&#34; Person&#34;将setup方法本身与命令相关联(这意味着,当您更改spinbox中的值时,它可能会设置一个新的 - 没有任何东西可用)。但是我发现,spinbox的构造函数会自动触发命令函数本身。意味着输出将是:
&#34; _select_event,mark0,_select_event&#34; (mark0不再被触发,因为if条件现在不再是真的,因此幸运地预测无限递归)。
当然self.event_edit_widget_id_spinbox.delete(0,tkinter.END) 不起作用,并在_select_event的第二次调用中引发异常,这是由旋转框的构造函数触发的。如何防止此构造函数在安装时触发命令?