Ukraine's grain exports have been transiting through the EU to other countries since the war-torn nation's traditional Black Sea routes were blocked by Russia's invasion.
But because of logistical issues, the grain had been piling up and driving down prices, which led to protests from farmers and the resignation of Poland's agriculture minister.
“Today the government decided on a regulation to ban the entry, imports of grain into Poland, as well as of dozens of other kinds of food,” the governing party's leader Jaroslaw Kaczynski said on Saturday.
Otherwise “it would lead to a far-reaching crisis of Poland's farming sector … We have to protect Polish agriculture,” he added.
Speaking at a convention of his right-wing Law and Justice party in the northern village of Lyse, Mr Kaczynski stressed that Poland remained a staunch supporter of neighbouring Ukraine.
“We remain, without even the slightest change, friends and allies of Ukraine,” he said.
In a similar announcement, Hungarian Agriculture Minister Istvan Nagy also said in a Facebook message that Hungary was banning the import of agricultural products from Ukraine.
Both Warsaw and Budapest said that their bans will last until June 30.
In Poland, the ban will apply to imports of grain, sugar, meat, fruits and vegetables, milk, eggs and other foods.
Grain, oilseeds and several other agricultural products will be banned, a Hungarian agriculture ministry statement said.
Responding to Poland's announcement, Ukraine's Ministry of Agrarian Policy and Food said on Saturday that it “regrets the decision”.
“Polish farmers are facing a difficult situation, but we emphasise that Ukrainian farmers are facing the most difficult situation” given the war, it added.
The ministry proposed for the two countries to come to a new agreement in the coming days that would satisfy both sides.
Polish government spokesman Piotr Muller told the PAP news outlet that “we are open to other actions that could stabilise the situation".
Budapest said that during the ban period “the government expects a permanent solution and the adoption of EU measures”.
Hungary “is committed to representing the interests of the Hungarian farming community,” it added.
Last month, Poland and Hungary were among several European countries that requested help from the EU to counter the impact of cheap Ukrainian grain.