0

I'm trying to add a function to each button but when i do, the function opens immediately without me pressing the button in the menu.

Hello, i'm new to programming and i'm trying to learn some basic about creating a menu for a notepad, so far i learned how to create the menu and the buttons inside of it, I'm trying to add a function to each button but when i do, the function opens immediately without me pressing the button in the menu, the only thing that have worked so far is to try the lambda function, but i want to be able to write the function without having to write the whole code for the function after the lambda function.

from tkinter import Tk, scrolledtext, Menu, filedialog
from tkinter.scrolledtext import ScrolledText
from tkinter import*


#Root main window
root = Tk(className=" Text Editor")
textarea = ScrolledText(root, width=80, height=100)
textarea.pack()

# Menu options
menu = Menu(root)
root.config(menu=menu)
filename = Menu(menu)
edicion = Menu(menu)


# Funciones

def open_file ():
    file = filedialog.askopenfiles(parent=root, mode='rb', title="Select a file")
    if file != None:
        contenidos = file.read()
        textarea.insert('1.0', contenidos)
        file.close

menu.add_cascade(label="File", menu=filename)
filename.add_command(label="New")
filename.add_command(label="Open", command= open_file)

filename.add_command(label="Save")
filename.add_separator()
filename.add_command(label="Exit")
menu.add_cascade(label="Editar", menu=edicion)
edicion.add_command(label="Cortar")
edicion.add_command(label="Pegar")
edicion.add_command(label="Copiar")
textarea.pack()

root.mainloop()

1 Answers1

0

In this line:

filename.add_command(label="Open", command= open_file())

you do not want the extra () after your command, that will call your function. Try without:

filename.add_command(label="Open", command= open_file)
Hoog
  • 2,280
  • 1
  • 14
  • 20