这些代码可不可以写到一个def函数里面
时间: 2024-02-27 14:56:05 浏览: 16
当然可以把这些代码写到一个函数里面。以下是一个示例函数:
```python
import os
import json
import tkinter as tk
from tkinter import scrolledtext
def show_json_file_content(folder_path, file_name):
def read_json_file(file_path):
# 读取JSON文件内容
with open(file_path, "r", encoding="utf-8") as f:
content = json.load(f)
return content
# 创建界面
window = tk.Tk()
window.title("JSON文件内容展示")
st = scrolledtext.ScrolledText(window, width=80, height=30)
st.pack()
# 读取JSON文件内容并显示
file_path = os.path.join(folder_path, file_name)
content = read_json_file(file_path)
st.insert(tk.END, json.dumps(content, indent=4, ensure_ascii=False))
window.mainloop()
if __name__ == "__main__":
# 指定文件夹路径和文件名
folder_path = "/path/to/folder"
file_name = "2659483.json"
show_json_file_content(folder_path, file_name)
```
在这个函数中,`read_json_file`函数和`show_json_file_content`函数被合并成了一个函数。`show_json_file_content`函数接受两个参数:`folder_path`表示文件夹路径,`file_name`表示要展示的JSON文件名。函数中的代码和之前的代码类似,只是把变量替换成了函数参数。
需要注意的是,这个函数只展示了一个文件的内容,如果需要展示多个文件的内容,可以在函数中添加遍历文件的代码,并调用`show_json_file_content`函数展示每个文件的内容。