The attack in Pul-i-Alam, capital of volatile Logar province, also left 23 prosecutors wounded as they were meeting to decide the fate of six newly arrested Taliban militants.
The head of the court was among those killed in the attack, which comes as the Taliban step up their annual spring offensive after naming a new leader late last month.
"Three gunmen entered the court building and started shooting people at close range," Salim Saleh, the provincial governor's spokesman, told AFP.
Hasib Stanakzai, a member of Logar's provincial council, confirmed the death toll.
More From This Section
The Taliban said the attack was in retaliation for the execution of six Taliban-linked inmates in early May, part of President Ashraf Ghani's new hardline policy against the insurgents.
"The martyrdom attack was carried out in revenge for the execution of our mujahideen," Taliban spokesman Zabihullah Mujahid said on Twitter.
The violence underscores Afghanistan's fragile security situation as the militants intensify attacks against the Western-backed government.
On June 1 Taliban suicide bombers wearing police uniforms raided a courthouse in the eastern city of Ghazni, killing six people.
The Taliban on the same day announced Haibatullah Akhundzada as their new leader, elevating a low-profile religious figure in a swift power transition after officially confirming the death of Mullah Mansour in a US drone strike.
The drone attack was the first known American assault on a top Afghan Taliban leader on Pakistani soil.
Observers say Akhundzada, who is seen as more of a spiritual figurehead than a military commander, will emulate Mansour in shunning peace talks and intensifying attacks against the Afghan government.