我需要复制一个类别从一个项目到另一个项目。为此,我创建了一个包含三个字段的简单GUI。对于项目,我目前有一个静态下拉列表。但是对于这些类别,我希望有一个下拉列表,根据上面选择的项目。不知何故,Tkinter不认识(或阅读)我的输入:
#get project FROM which the information gets copied
Label(screen, text = "From project").grid(column=0, row=1, padx=10, pady=10)
proj_id=OptionMenu(screen, clicked_proj_from, '1001', '1002')
proj_id.grid(column=1, row=1)
project_from = clicked_proj_from.get()
#get project TO which the information gets copied
Label(screen, text = "To project").grid(column=0, row=2, padx=10, pady=10)proj_id=OptionMenu(screen, clicked_proj_to, '1001', '1002')
proj_id.grid(column=1, row=2)
project_to = clicked_proj_to.get()
#get attribute category
clicked_attr=[]
attr=get_category(project_from)
for attribut in attr.items:
clicked_attr.append(attribut.name)
variable.set(clicked_attr[0])
Label(screen, text = "Attribute_category").grid(column=0, row=3, padx=10, pady=10)
attr_cat = OptionMenu(screen, variable, *clicked_attr)
attr_cat.grid(column=1, row=3)
category = variable.get()
screen.mainloop()
我写的是1001,而不仅仅是project_from
:
attr=get_category(project_from),
代码可以工作,但否则我会得到一个值丢失的错误。
我怎样才能改变这个密码?
提前谢谢你!
发布于 2019-08-07 00:58:32
这是因为您在启动project_from = clicked_proj_from.get()
“来自选项菜单的项目”之后立即执行了,project_from
应该是None
,因为目前没有选择任何选项。
您应该在分配给选项command
的回调函数中这样做。下面是您的代码的更新版本,作为示例:
# function will be executed when project from is changed
def on_project_change(project_from):
attr = get_category(project_from)
menu = attr_cat['menu']
# clear the optionmenu
menu.delete(0, 'end')
# add new attribute to optionmenu
for attribute in attr.items:
menu.add_command(label=attribute.name, command=lambda val=attribute.name: variable.set(val))
# reset optionmenu selection
variable.set('')
screen = Tk()
clicked_proj_from = StringVar()
clicked_proj_to = StringVar()
variable = StringVar()
projects = ('1001', '1002')
Label(screen, text='From project').grid(row=1, column=0, padx=10, pady=10)
OptionMenu(screen, clicked_proj_from, *projects, command=on_project_change).grid(row=1, column=1)
Label(screen, text='To project').grid(row=2, column=0, padx=10, pady=10)
OptionMenu(screen, clicked_proj_to, *projects).grid(row=2, column=1)
Label(screen, text='Attribute categories').grid(row=3, column=0, padx=10, pady=10)
attr_cat = OptionMenu(screen, variable, None)
attr_cat.grid(row=3, column=1)
screen.mainloop()
https://stackoverflow.com/questions/57378977
复制相似问题