The gunmen stormed a provincial court in Pul-i-Alam, said Saleem Saleh, spokesman for the governor of eastern Logar province. Pul-i-Alam is the capital of Logar province, about 70 kilometers (43 miles) south of Kabul.
The attack triggered a shootout with Afghan security forces that lasted 1 1/2 hours. At least 23 people were wounded.
The seven killed included the director of the provincial attorney general's office, Saleh said. Authorities did not specify how many other prosecutors and judges were killed.
In a series of Twitter messages, the Taliban made their motive clear.
"This was in retaliation for the execution of six martyred Taliban fighters," according to a tweet from Taliban spokesman Zabiullah Mujahid.
A spate of retaliatory attacks
Since the Afghan government executed six Taliban insurgents last month, the Taliban has claimed three attacks targeting judges, prosecutors and other court employees.
Last Wednesday, Taliban militants attacked an appellate court building and killed a police officer and five civilians, Afghan Interior Ministry spokesman Sediq Sediqqi said.
One suicide bomber detonated his explosives at the front gate of the court. Three would-be suicide bombers were killed in a gun battle with Afghan forces.
And on May 25, a suicide bomber in Kabul blew up a van carrying court workers. Eleven people were killed in that attack.
New leadership for the Taliban
After a U.S. drone strike killed Taliban leader Mullah Akhtar Mohammad Mansour
last month, the terror group named senior religious cleric Mawlawi Haibatullah Akhundzada as its new leader.
"It's a clever choice because (Akhundzada) is a religious scholar from the founder generation of the Taliban," said Thomas Ruttig
of the Afghanistan Analysts' Network.
"He may therefore be able to integrate the younger and more militant generation."