如何一次销毁特定的小部件?编程

2024-09-30 18:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

当我按下“新建”按钮时,底部会出现一个提交按钮。但每当我选择下拉值时,提交按钮将被销毁,并显示一个名为“更新”的新按钮。但问题是,当我反复选择下拉值并返回“创建新”按钮时,“更新”按钮只能销毁一次。这是一种找到所有更新按钮并一次全部销毁的方法吗?谢谢

当我按下创建新按钮时:

enter image description here

当我选择几次下拉列表值并返回“新建”时,提交和更新按钮被堆叠在一起:

enter image description here

代码:

def submit():
    deleteAllEntry()
    global CreateJsonBtn, profilenameLbl, ProfileNameEntry
    CreateJsonBtn = Button(jsonframe, text="Submit", command=submit, width=11)
    CreateJsonBtn.place(x=370, y=540)
    CreateNewJsonBtn.configure(state=DISABLED)

    UpdateJsonBtn.destroy()

#Get value inside the dropdown value
def dropdown(choice):
    if (jsonprofileName == ""):
        tkMessageBox.showinfo("ERROR", "Fail to retrieve value. Try again later", icon="error")
    else:
        cursor = con.cursor()

        cursor.execute("select * from json where jsonprofilename='" +options.get() + "'")

        rows = cursor.fetchall()

        deleteAllEntry()
    global row
    for row in rows:
        insertAllEntry()

    cursor.close()

    try:
    #Delete submit button when select existing value
        CreateJsonBtn.destroy()
        CreateNewJsonBtn.configure(state=NORMAL)
    except:
        pass

    finally:
        global UpdateJsonBtn
        UpdateJsonBtn = Button(jsonframe, text="Update", command=submit, width=11)
        UpdateJsonBtn.place(x=370, y=550)






Tags: textvaluedefbuttonwidth按钮globalcursor
2条回答

所以我知道它应该与CreateJsonBtn.place_forget()一起工作

你可以试试

您可以配置按钮,而不是多次销毁和创建按钮,请查看下面的示例

from tkinter import *

def foo():
    print('called foo')
    button.configure(text='bar',command=bar)

def bar():
    print('called bar')
    button.configure(text='foo',command=foo)

root=Tk()

button=Button(root,text='foo',command=foo)
button.pack()

root.mainloop()

config/configure是一种通用的小部件方法,您可以使用thisreferenece了解更多有关它们的信息

您当前面临此问题的原因是,每次使用下拉列表时,都会在上一个按钮(如果已经存在)的上方放置一个新按钮“更新”。UpdateJsonBtn保存最后分配的实例,因此删除最上面的实例,如果底层有按钮,它们将不会被销毁。我不会建议您目前使用的方法

在您提出的问题中,如果有一种方法可以获取所有显示“更新”的按钮,您可以使用以下方法进行操作(同样,我不建议在您的案例中使用此方法,只是为了回答您的问题)

for widget in jsonframe.winfo_children():
    if isinstance(widget,Button):
        if widget['text']=='Update':
            widget.destroy()

相关问题 更多 >