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.
Taliban kill 16 bus passengers in northern Afghanistan: officials
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.
"Seven people were killed including Mohammad Akram Nejat, the newly appointed head of the court."
Hasib Stanakzai, a member of Logar's provincial council, confirmed the death toll.
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.
New Afghan Taliban leader vows no peace talks in audio recording
"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.
And on May 25, 11 people were killed in a Taliban suicide bombing that targeted court employees near Kabul.
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.
Six killed as Taliban bombers raid Afghan courthouse
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.
COMMENTS
Comments are moderated and generally will be posted if they are on-topic and not abusive.
For more information, please see our Comments FAQ