You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter应用二次编辑保存数据异常问题求助

问题:Tkinter编辑保存功能异常,重复编辑后旧保存按钮未销毁

我开发的Tkinter应用包含标签(Label)和输入框(Entry)组件,用户可编辑数据并通过保存按钮保存修改。但首次编辑保存后,再次编辑同一内容时,输入框和保存按钮功能异常。


初始edit_data相关代码

def save_data(text, i, j):

    global desc_frame
    info = text.get()

    if(len(info)==0):
        messagebox.showwarning("Warning", "No data to save")
    else:
        text.destroy()
        newinfo = tk.Label(desc_frame, text=info, font=('Helvetica', 15), bg="lightgray")
        newinfo.grid(row=i, column=1, pady=5)
        edit_buttons(i, j+1, newinfo)


def edit_data(newinfo, i, j):
    global desc_frame

    text = newinfo.cget("text")
    if len(text) == 0:
        messagebox.showwarning("Warning", "No data to edit")
    else:
        newinfo.destroy()
        newEntry = tk.Entry(desc_frame, font=('Helvetica', 15))
        newEntry.insert(0, text)
        newEntry.grid(row=i, column=j - 2, pady=5)

按钮相关代码

def save_buttons(i, j, text):

    global desc_frame

    image = Image.open("save3.png")
    image = ImageTk.PhotoImage(image)

    style = ttk.Style()
    style.configure("Custom.TButton", background="blue")

    savebtn = ttk.Button(desc_frame, image=image, style="Custom.TButton", command=lambda :save_data(text, i, j))
    savebtn.config(width=4)
    savebtn.image = image
    savebtn.grid(row=i, column=j, pady=5, columnspan=2)


def edit_buttons(i, j, newinfo):

    global  desc_frame

    style = ttk.Style()
    style.configure("Custom.TButton", background="blue")

    image1 = Image.open("edit.png")
    image1 = ImageTk.PhotoImage(image1)

    editbtn = ttk.Button(desc_frame, image=image1, style="Custom.TButton", command=lambda : edit_data(newinfo, i, j))
    editbtn.config(width=4)
    editbtn.image = image1
    editbtn.grid(row=i, column=j, pady=5, padx=20, columnspan=2)

尝试修改后的edit_data函数

def edit_data(newinfo, i, j):
    global desc_frame

    text = newinfo.cget("text")
    if len(text) == 0:
        messagebox.showwarning("Warning", "No data to edit")
    else:
        newinfo.destroy()
        newEntry = tk.Entry(desc_frame, font=('Helvetica', 15))
        newEntry.insert(0, text)
        newEntry.grid(row=i, column=j - 2, pady=5)

        existing_save_btn = get_widget_by_row_column(desc_frame, i, j)
        if existing_save_btn:
            existing_save_btn.destroy()
        save_buttons(i, j, newEntry)

辅助函数

def get_widget_by_row_column(frame, row, column):
    for widget in frame.winfo_children():
        if widget.grid_info()["row"] == row and widget.grid_info()["column"] == column:
            return widget
    return None

当前问题

修改后点击编辑按钮会生成新保存按钮,但旧按钮未被销毁,仅新按钮可执行保存操作。

内容的提问来源于stack exchange,提问作者rayen samali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:12:40