使用PyQt5写python代码读取字典中的key以及key里面嵌套的key,将其设置为子节点和下一子节点,并生成图形化界面
时间: 2024-06-10 17:05:58 浏览: 94
可以使用QTreeWidget来生成图形化界面,可以使用以下代码来读取字典中的key以及key里面嵌套的key,并将其设置为QTreeWidget的子节点和下一子节点。
```python
import sys
from PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
def addTreeItems(parent, data):
for key, value in data.items():
child = QTreeWidgetItem(parent)
child.setText(0, str(key))
if isinstance(value, dict):
addTreeItems(child, value)
else:
sub_child = QTreeWidgetItem(child)
sub_child.setText(0, str(value))
data = {"key1": {"subkey1a": "value1a", "subkey1b": "value1b"}, "key2": "value2"}
app = QApplication(sys.argv)
tree = QTreeWidget()
addTreeItems(tree, data)
tree.show()
sys.exit(app.exec_())
```
此代码可以将如下字典生成为图形化界面:
```
{
"key1": {"subkey1a": "value1a", "subkey1b": "value1b"},
"key2": "value2"
}
```
生成的图形化界面如下图所示:
![image](https://cdn.nlark.com/yuque/0/2021/png/3136245/1631919896385-5d5f5f89-ead2-4018-a863-cfedf9d908f5.png)
阅读全文