0

我正在使用 Tkinter 在 Python 中制作一个文本编辑器,现在我正在执行 New 按钮,但是当我按下该按钮时,它会在我单击“YES”按钮之前删除所有内容。有代码:

def new():
   pop_up_new = Tk()
   lb_new = Label(pop_up_new, text="Are you sure to delete?")
   bt_new = Button(pop_up_new, text="Yes", command=text.delete(END, '1.0'))
   bt_new_no = Button(pop_up_new, text="No", command=pop_up_new.destroy)
   lb_new.grid()
   bt_new.grid(row =1 , column = 0, sticky = W)
   bt_new_no.grid(row = 1, column = 1, sticky = W)


text = Text(window)
text.pack()

menubar = Menu(window)
filemenu = Menu(menubar, tearoff = 1)
filemenu.add_command(label="Open")
filemenu.add_command(label="Save")
filemenu.add_command(label="New", command=new)
filemenu.add_separator()
filemenu.add_command(label="Exit")
menubar.add_cascade(label="File", menu=filemenu)
window.config(menu=menubar)
4

1 回答 1

0

text.delete()当您尝试将其作为对象的命令传递时,实际上会调用以下代码Button

Button(pop_up_new, text="Yes", command=text.delete(END, '1.0'))

由于删除显然不需要参数,因此您可以轻松使用 lambda 函数:

..., command=lambda : text.delete(END, '1.0'))

它创建了一个函数,该函数调用text.delete()并将这个新函数作为 的值传递command

或者,您可以定义自己的函数并将其作为命令传递:

def delete_text():
    text.delete(END, '1.0')


..., command=delete_text))

在这两种情况下,都会引用全局变量text,因此您应该考虑重构代码以尽可能使用类。

于 2018-06-13T11:12:46.273 回答