简体   繁体   English

Tkinter Python-根据Comboxbox的条件删除小部件

[英]Tkinter Python - Remove Widgets based on Comboxbox condition

I am trying to write a Python Tkinter program to display/remove a Label and Entry based on Combobox condition, it is working fine for display but for remove/hide it is not working. 我正在尝试编写一个Python Tkinter程序来基于组合框条件显示/删除标签和条目,它可以很好地显示,但不能删除/隐藏。

def on_field_change(index, value, op):
    var_select_combo = box.current()
    serv_label = Label(frame1, text="Servive Name")
    E3 = Entry(frame1, bd=5)
    if var_select_combo == 1:
        serv_label.grid(row=3)
        E3.grid(row=3, column=1, pady=10)
    if var_select_combo == 0:
        serv_label.grid_forget()
        E3.grid_forget()

L3 = Label(frame1, text="Database")
L3.grid(row=0,pady=10)
box_value = StringVar()
box_value.trace('w',on_field_change)
box = ttk.Combobox(frame1, text="Database", textvariable=box_value,
                            state='readonly')
box['values'] = ('Teradata','Oracle')
box.current(0)
box.grid(column=1, row=0,pady=10)

You have to create widgets inside if and you have to assign them to global variables. 您必须在if创建小部件if并且必须将它们分配给全局变量。

Now when you choose to remove you create second pair of widgets (because you create it before if ) and then you remove this second pair but first pair is still visible - but you don't have access to first pair because you didn't assign them to global variables. 现在,当您选择删除时,您将创建第二对小部件(因为您在if之前创建了它),然后删除了第二对小部件,但第一对仍然可见-但是您无法访问第一对小部件,因为您没有分配他们到全局变量。

You can also create widgets only once - at start - and later only show and hide it. 您也只能创建一次小部件-在开始时-以后仅显示和隐藏它。

def on_field_change(index, value, op):
    var_select_combo = box.current()
    if var_select_combo == 1:
        serv_label.grid(row=3)
        E3.grid(row=3, column=1, pady=10)
    else:
        serv_label.grid_forget()
        E3.grid_forget()

# create at start assigned to global variables
serv_label = Label(frame1, text="Servive Name")
E3 = Entry(frame1, bd=5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM