0

I'm making a text editor in Python with Tkinter, and now I'm doing the New button, but when I press that button it deletes all before i click the button "YES". There's the code:

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)
Pandorolo
  • 21
  • 7
  • Possible duplicate of [Why is Button parameter “command” executed when declared?](https://stackoverflow.com/questions/5767228/why-is-button-parameter-command-executed-when-declared) – fhdrsdg Jun 13 '18 at 11:14

1 Answers1

0

In the following code text.delete() is actually called when you try to pass it as the command for the Button object:

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

Since there there are no parameters apparently required for the deletion you can easily use a lambda function:

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

which creates a function that calls text.delete() and passes this new function as the value of command.

Alternatively you could define your own function and pass it as the command:

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


..., command=delete_text))

In both cases the global variable text is referenced so you should consider refactoring your code to use classes if possible.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • It Works with lambda! Thank You! – Pandorolo Jun 13 '18 at 11:19
  • @EugenioAmatoNadaia: no problem. You're new here so you might want to check out https://stackoverflow.com/help/someone-answers. You should also check out the accepted answer to the [duplicate question](https://stackoverflow.com/questions/5767228/why-is-button-parameter-command-executed-when-declared) that fhdrsdg found as it explains things better than I have above. – mhawke Jun 13 '18 at 11:24