python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python内置函数解析工具

使用Python开发一个内置函数大全解析工具(附源码)

作者:小庄-Python办公

这篇文章主要为大家详细介绍了如何使用Python开发一个内置函数大全解析工具,包含了Python所有常用内置函数的详细解析、演示代码和交互式查询功能,希望对大家有所帮助

前言

这是一个全面的Python内置函数学习和参考工具集,包含了Python所有常用内置函数的详细解析、演示代码和交互式查询功能。

功能特性

1. 全面的函数覆盖

2. 多种查询工具

命令行工具 (interactive_builtin_explorer.py)

GUI图形界面 (gui_builtin_explorer.py)

3. 完整的测试验证

使用方法

交互式查询

命令行版本:

# 运行命令行交互式工具
gui_builtin_explorer.py

交互式命令:

GUI图形界面版本:

# 运行GUI图形界面工具
gui_builtin_explorer.py

GUI操作说明:

运行测试

# 运行完整测试套件
gui_builtin_explorer.py

支持的内置函数分类

数学运算 (13个)

类型转换 (8个)

bool(), bytes(), str(), list(), tuple(), set(), dict(), frozenset()

序列操作 (8个)

len(), sorted(), reversed(), enumerate(), zip(), slice(), range(), memoryview()

迭代器 (6个)

iter(), next(), filter(), map(), all(), any()

输入输出 (3个)

print(), input(), open()

对象操作 (31个)

使用示例

示例1:查找字符串相关函数

gui_builtin_explorer.py

示例2:学习数学函数

gui_builtin_explorer.py

示例3:验证函数功能

gui_builtin_explorer.py

项目统计

技术特点

学习建议

效果图

源代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python内置函数GUI浏览器

基于tkinter的图形界面工具,提供直观的函数浏览和学习体验。
用户可以通过点击函数名查看详细信息和示例代码。

功能特性:
- 分类浏览内置函数
- 点击查看函数详细信息
- 实时代码演示
- 搜索功能
- 美观的GUI界面

作者: AI助手
创建时间: 2024
"""

import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import sys
import io
from contextlib import redirect_stdout, redirect_stderr
from python_builtin_functions import PythonBuiltinFunctions

class BuiltinFunctionGUI:
    """
    Python内置函数GUI浏览器
    
    提供图形界面来浏览和学习Python内置函数
    """
    
    def __init__(self, root):
        self.root = root
        self.parser = PythonBuiltinFunctions()
        self.current_function = None
        
        # 设置窗口
        self.setup_window()
        
        # 创建界面
        self.create_widgets()
        
        # 加载数据
        self.load_functions()
    
    def setup_window(self):
        """
        设置主窗口
        """
        self.root.title("Python内置函数大全 - GUI浏览器")
        self.root.geometry("1200x800")
        self.root.minsize(1000, 600)
        
        # 设置图标和样式
        try:
            self.root.iconbitmap(default="python.ico")
        except:
            pass  # 如果没有图标文件就忽略
        
        # 配置样式
        style = ttk.Style()
        style.theme_use('clam')
    
    def create_widgets(self):
        """
        创建界面组件
        """
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=2)
        main_frame.rowconfigure(1, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="🐍 Python内置函数大全", 
                               font=('Arial', 16, 'bold'))
        title_label.grid(row=0, column=0, columnspan=3, pady=(0, 10))
        
        # 左侧面板 - 函数列表
        self.create_function_list_panel(main_frame)
        
        # 右侧面板 - 详细信息
        self.create_detail_panel(main_frame)
        
        # 底部面板 - 代码演示
        self.create_demo_panel(main_frame)
    
    def create_function_list_panel(self, parent):
        """
        创建函数列表面板
        """
        # 左侧框架
        left_frame = ttk.LabelFrame(parent, text="📚 函数列表", padding="5")
        left_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=(0, 5))
        left_frame.columnconfigure(0, weight=1)
        left_frame.rowconfigure(2, weight=1)
        
        # 搜索框
        search_frame = ttk.Frame(left_frame)
        search_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 5))
        search_frame.columnconfigure(1, weight=1)
        
        ttk.Label(search_frame, text="🔍 搜索:").grid(row=0, column=0, padx=(0, 5))
        self.search_var = tk.StringVar()
        self.search_var.trace('w', self.on_search_change)
        search_entry = ttk.Entry(search_frame, textvariable=self.search_var)
        search_entry.grid(row=0, column=1, sticky=(tk.W, tk.E))
        
        # 分类选择
        category_frame = ttk.Frame(left_frame)
        category_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 5))
        category_frame.columnconfigure(1, weight=1)
        
        ttk.Label(category_frame, text="📂 分类:").grid(row=0, column=0, padx=(0, 5))
        self.category_var = tk.StringVar()
        self.category_combo = ttk.Combobox(category_frame, textvariable=self.category_var,
                                          state="readonly")
        self.category_combo.grid(row=0, column=1, sticky=(tk.W, tk.E))
        self.category_combo.bind('<<ComboboxSelected>>', self.on_category_change)
        
        # 函数列表
        list_frame = ttk.Frame(left_frame)
        list_frame.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        list_frame.columnconfigure(0, weight=1)
        list_frame.rowconfigure(0, weight=1)
        
        # 创建Treeview
        self.function_tree = ttk.Treeview(list_frame, columns=('category',), show='tree headings')
        self.function_tree.heading('#0', text='函数名')
        self.function_tree.heading('category', text='分类')
        self.function_tree.column('#0', width=120)
        self.function_tree.column('category', width=100)
        
        # 滚动条
        tree_scroll = ttk.Scrollbar(list_frame, orient="vertical", command=self.function_tree.yview)
        self.function_tree.configure(yscrollcommand=tree_scroll.set)
        
        self.function_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        tree_scroll.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 绑定选择事件
        self.function_tree.bind('<<TreeviewSelect>>', self.on_function_select)
    
    def create_detail_panel(self, parent):
        """
        创建详细信息面板
        """
        # 右侧框架
        right_frame = ttk.LabelFrame(parent, text="📖 函数详情", padding="5")
        right_frame.grid(row=1, column=1, sticky=(tk.W, tk.E, tk.N, tk.S), padx=5)
        right_frame.columnconfigure(0, weight=1)
        right_frame.rowconfigure(5, weight=1)
        
        # 函数名
        self.func_name_var = tk.StringVar(value="请选择一个函数")
        func_name_label = ttk.Label(right_frame, textvariable=self.func_name_var,
                                   font=('Arial', 14, 'bold'), foreground='blue')
        func_name_label.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 描述
        ttk.Label(right_frame, text="📝 描述:", font=('Arial', 10, 'bold')).grid(row=1, column=0, sticky=tk.W)
        self.description_var = tk.StringVar()
        description_label = ttk.Label(right_frame, textvariable=self.description_var,
                                     wraplength=400, justify=tk.LEFT)
        description_label.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 语法
        ttk.Label(right_frame, text="⚙️ 语法:", font=('Arial', 10, 'bold')).grid(row=3, column=0, sticky=tk.W)
        self.syntax_var = tk.StringVar()
        syntax_label = ttk.Label(right_frame, textvariable=self.syntax_var,
                                font=('Consolas', 9), foreground='darkgreen',
                                wraplength=400, justify=tk.LEFT)
        syntax_label.grid(row=4, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 参数说明
        ttk.Label(right_frame, text="📋 参数:", font=('Arial', 10, 'bold')).grid(row=5, column=0, sticky=(tk.W, tk.N))
        
        # 参数文本框
        param_frame = ttk.Frame(right_frame)
        param_frame.grid(row=6, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
        param_frame.columnconfigure(0, weight=1)
        param_frame.rowconfigure(0, weight=1)
        
        self.param_text = scrolledtext.ScrolledText(param_frame, height=4, wrap=tk.WORD,
                                                   font=('Arial', 9))
        self.param_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 返回类型
        ttk.Label(right_frame, text="↩️ 返回类型:", font=('Arial', 10, 'bold')).grid(row=7, column=0, sticky=tk.W)
        self.return_type_var = tk.StringVar()
        return_type_label = ttk.Label(right_frame, textvariable=self.return_type_var,
                                     font=('Arial', 9), foreground='purple')
        return_type_label.grid(row=8, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
    
    def create_demo_panel(self, parent):
        """
        创建代码演示面板
        """
        # 底部框架
        bottom_frame = ttk.LabelFrame(parent, text="🎭 代码演示", padding="5")
        bottom_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(10, 0))
        bottom_frame.columnconfigure(0, weight=1)
        bottom_frame.rowconfigure(1, weight=1)
        
        # 按钮框架
        button_frame = ttk.Frame(bottom_frame)
        button_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 5))
        
        # 运行演示按钮
        self.demo_button = ttk.Button(button_frame, text="▶️ 运行演示", 
                                     command=self.run_demo, state='disabled')
        self.demo_button.grid(row=0, column=0, padx=(0, 10))
        
        # 清空输出按钮
        clear_button = ttk.Button(button_frame, text="🗑️ 清空输出", 
                                 command=self.clear_output)
        clear_button.grid(row=0, column=1)
        
        # 示例代码标签
        self.example_var = tk.StringVar()
        example_label = ttk.Label(button_frame, textvariable=self.example_var,
                                 font=('Consolas', 9), foreground='darkblue')
        example_label.grid(row=0, column=2, padx=(20, 0))
        
        # 输出文本框
        output_frame = ttk.Frame(bottom_frame)
        output_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        output_frame.columnconfigure(0, weight=1)
        output_frame.rowconfigure(0, weight=1)
        
        self.output_text = scrolledtext.ScrolledText(output_frame, height=8, wrap=tk.WORD,
                                                    font=('Consolas', 9), bg='#f0f0f0')
        self.output_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
    
    def load_functions(self):
        """
        加载函数数据
        """
        # 获取所有分类
        categories = set()
        for info in self.parser.functions_info.values():
            categories.add(info['category'])
        
        # 设置分类下拉框
        category_list = ['全部'] + sorted(list(categories))
        self.category_combo['values'] = category_list
        self.category_combo.set('全部')
        
        # 加载所有函数
        self.refresh_function_list()
    
    def refresh_function_list(self, search_text='', category='全部'):
        """
        刷新函数列表
        
        Args:
            search_text: 搜索文本
            category: 选择的分类
        """
        # 清空现有项目
        for item in self.function_tree.get_children():
            self.function_tree.delete(item)
        
        # 过滤函数
        filtered_functions = []
        for func_name, info in self.parser.functions_info.items():
            # 分类过滤
            if category != '全部' and info['category'] != category:
                continue
            
            # 搜索过滤
            if search_text and search_text.lower() not in func_name.lower():
                continue
            
            filtered_functions.append((func_name, info))
        
        # 按函数名排序
        filtered_functions.sort(key=lambda x: x[0])
        
        # 添加到树形控件
        for func_name, info in filtered_functions:
            self.function_tree.insert('', 'end', text=func_name, 
                                     values=(info['category'],), tags=(func_name,))
    
    def on_search_change(self, *args):
        """
        搜索文本变化事件
        """
        search_text = self.search_var.get()
        category = self.category_var.get()
        self.refresh_function_list(search_text, category)
    
    def on_category_change(self, event):
        """
        分类选择变化事件
        """
        search_text = self.search_var.get()
        category = self.category_var.get()
        self.refresh_function_list(search_text, category)
    
    def on_function_select(self, event):
        """
        函数选择事件
        """
        selection = self.function_tree.selection()
        if not selection:
            return
        
        item = selection[0]
        func_name = self.function_tree.item(item, 'text')
        
        if func_name in self.parser.functions_info:
            self.show_function_details(func_name)
    
    def show_function_details(self, func_name):
        """
        显示函数详细信息
        
        Args:
            func_name: 函数名
        """
        self.current_function = func_name
        info = self.parser.functions_info[func_name]
        
        # 更新界面
        self.func_name_var.set(f"{func_name}()")
        self.description_var.set(info['description'])
        self.syntax_var.set(info['syntax'])
        self.return_type_var.set(info['return_type'])
        self.example_var.set(f"示例: {info['example']}")
        
        # 更新参数说明
        self.param_text.delete(1.0, tk.END)
        self.param_text.insert(1.0, info['parameters'])
        
        # 启用演示按钮
        self.demo_button.config(state='normal')
    
    def run_demo(self):
        """
        运行函数演示
        """
        if not self.current_function:
            return
        
        try:
            # 捕获输出
            stdout_capture = io.StringIO()
            stderr_capture = io.StringIO()
            
            with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
                self.parser._run_demonstration(self.current_function)
            
            stdout_output = stdout_capture.getvalue()
            stderr_output = stderr_capture.getvalue()
            
            # 显示输出
            self.output_text.insert(tk.END, f"\n=== {self.current_function}() 演示 ===\n")
            
            if stdout_output:
                self.output_text.insert(tk.END, stdout_output)
            
            if stderr_output:
                self.output_text.insert(tk.END, f"错误输出:\n{stderr_output}")
            
            self.output_text.insert(tk.END, "\n" + "="*50 + "\n")
            
            # 滚动到底部
            self.output_text.see(tk.END)
        
        except Exception as e:
            self.output_text.insert(tk.END, f"\n演示运行出错: {str(e)}\n")
            self.output_text.see(tk.END)
    
    def clear_output(self):
        """
        清空输出
        """
        self.output_text.delete(1.0, tk.END)
        self.output_text.insert(1.0, "📋 输出区域已清空,点击'运行演示'查看函数演示结果\n")


def main():
    """
    主函数
    """
    # 创建主窗口
    root = tk.Tk()
    
    # 创建应用
    app = BuiltinFunctionGUI(root)
    
    # 设置初始提示
    app.output_text.insert(1.0, 
        "🎉 欢迎使用Python内置函数GUI浏览器!\n\n"
        "📚 使用说明:\n"
        "1. 在左侧选择函数分类或使用搜索功能\n"
        "2. 点击函数名查看详细信息\n"
        "3. 点击'运行演示'查看函数使用示例\n"
        "4. 在此区域查看演示输出结果\n\n"
        "💡 提示: 选择一个函数开始探索吧!\n"
        "="*50 + "\n"
    )
    
    # 运行主循环
    root.mainloop()


if __name__ == "__main__":
    main()

总结

欢迎提交问题和改进建议!如果发现函数信息有误或需要添加新功能,请:

以上就是使用Python开发一个内置函数大全解析工具(附源码)的详细内容,更多关于Python内置函数解析工具的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文