吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1103|回复: 16
收起左侧

[Python 原创] 色环电阻计算器PY版和HTML版代码。

  [复制链接]
vocan 发表于 2024-9-24 19:25
本帖最后由 vocan 于 2024-9-25 10:05 编辑

网页版

网页版
网页版代码,感谢反馈的BUG,在win7平台的IE11下发现问题是因为IE不支持 Array.from(),这是修正后的代码,
[HTML] 纯文本查看 复制代码
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>色环电阻计算器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .color-box {
            display: inline-block;
            width: 50px;
            height: 50px;
            margin: 5px;
            border: 1px solid #000;
        }
        #colorInputs {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <h1>色环电阻计算器</h1>
     
    <label for="num_bands">选择色环数量:</label>
    <select id="num_bands">
        <option value="4">四色环</option>
        <option value="5">五色环</option>
        <option value="6">六色环</option>
    </select>
     
    <div id="colorInputs">
        <label>选择颜色:</label>
        <div id="colorInputFields"></div>
    </div>
     
    <button type="button">计算</button>
     
    <h2>计算结果:</h2>
    <p id="result"></p>
    <div id="colorBlocks"></div>
 
    <script>
        const colorMap = {
            "黑": 0, "棕": 1, "红": 2, "橙": 3,
            "黄": 4, "绿": 5, "蓝": 6, "紫": 7,
            "灰": 8, "白": 9, "金": 0, "银": 0
        };
 
        const toleranceMap = {
            "黑": 0, "棕": 1, "红": 2, "橙": 3,
            "黄": 4, "绿": 0.5, "蓝": 0.25, "紫": 0.1,
            "灰": 0.05, "白": 0, "金": 5, "银": 10
        };

        function updateColorInputs() {
            const numBands = document.getElementById('num_bands').value;
            const colorInputFields = document.getElementById('colorInputFields');
            colorInputFields.innerHTML = ''; // 清空已有输入框
            for (let i = 0; i < numBands; i++) {
                addColorInput();
            }
        }
 
        function addColorInput() {
            const colorInputFields = document.getElementById('colorInputFields');
            const select = document.createElement('select');
            select.name = 'colors';
            const colors = Object.keys(colorMap);
            colors.forEach(function(color) {
                const option = document.createElement('option');
                option.value = color;
                option.text = color;
                select.appendChild(option);
            });
            colorInputFields.appendChild(select);
        }
 
        function calculateResistor() {
            const numBands = document.getElementById('num_bands').value;
            const colorInputs = document.querySelectorAll('#colorInputFields select');
            const colorCodes = Array.prototype.map.call(colorInputs, function(select) {
                return colorMap[select.value];
            });
            const toleranceColor = colorInputs[colorInputs.length - 1].value; // 最后一条颜色表示误差
            const tolerancePercentage = toleranceMap[toleranceColor]; // 获取误差百分比
 
            let resistorValue;
            if (numBands == 4) {
                resistorValue = (colorCodes[0] * 10 + colorCodes[1]) * Math.pow(10, colorCodes[2]);
            } else if (numBands == 5 || numBands == 6) {
                resistorValue = (colorCodes[0] * 100 + colorCodes[1] * 10 + colorCodes[2]) * Math.pow(10, colorCodes[3]);
            }
 
            const toleranceValue = resistorValue * (tolerancePercentage / 100);
            const minValue = (resistorValue - toleranceValue).toFixed(2);
            const maxValue = (resistorValue + toleranceValue).toFixed(2);
 
            document.getElementById('result').innerText = resistorValue + ' 欧姆 (±' + tolerancePercentage + '%) , 取值范围: ' + minValue + ' 欧姆 - ' + maxValue + ' 欧姆';
            displayColorBlocks(colorInputs);
        }
 
        function displayColorBlocks(colorInputs) {
            const colorBlocks = document.getElementById('colorBlocks');
            colorBlocks.innerHTML = ''; // 清空之前的颜色块
            Array.prototype.forEach.call(colorInputs, function(select) {
                const color = select.value;
                const colorBox = document.createElement('div');
                colorBox.className = 'color-box';
                colorBox.style.backgroundColor = getColorHex(color);
                colorBlocks.appendChild(colorBox);
            });
        }
 
        function getColorHex(color) {
            switch (color) {
                case "黑": return "#000000";
                case "棕": return "#964B00";
                case "红": return "#FF0000";
                case "橙": return "#FFA500";
                case "黄": return "#FFFF00";
                case "绿": return "#008000";
                case "蓝": return "#0000FF";
                case "紫": return "#800080";
                case "灰": return "#808080";
                case "白": return "#FFFFFF";
                case "金": return "#FFD700";
                case "银": return "#C0C0C0";
                default: return "#FFFFFF";
            }
        }
 
        // 初始化时根据选择的色环数量生成输入框
        window.onload = function() {
            updateColorInputs();
        };
    </script>
</body>
</html>

image.png PY代码:
[Python] 纯文本查看 复制代码
 import tkinter as tk
from tkinter import ttk

def get_color_code():
    return {
        "黑": 0, "棕": 1, "红": 2, "橙": 3,
        "黄": 4, "绿": 5, "蓝": 6, "紫": 7,
        "灰": 8, "白": 9, "金": 0, "银": 0
    }

def get_tolerance_map():
    return {
        "黑": 0, "棕": 1, "红": 2, "橙": 3,
        "黄": 4, "绿": 0.5, "蓝": 0.25, "紫": 0.1,
        "灰": 0.05, "白": 0, "金": 5, "银": 10
    }

def rgb_to_hex(color):
    """Convert color name to hex value."""
    color_codes = {
        "黑": "#000000", "棕": "#964B00", "红": "#FF0000",
        "橙": "#FFA500", "黄": "#FFFF00", "绿": "#008000",
        "蓝": "#0000FF", "紫": "#800080", "灰": "#808080",
        "白": "#FFFFFF", "金": "#FFD700", "银": "#C0C0C0"
    }
    return color_codes.get(color, "#FFFFFF")

def calculate_resistor(num_bands, selected_colors):
    color_map = get_color_code()
    tolerance_map = get_tolerance_map()
    
    # Convert colors to value codes
    color_codes = [color_map[color] for color in selected_colors]
    
    # Calculate resistance value
    if num_bands == 4:
        resistor_value = (color_codes[0] * 10 + color_codes[1]) * (10 ** color_codes[2])
    else:
        resistor_value = (color_codes[0] * 100 + color_codes[1] * 10 + color_codes[2]) * (10 ** color_codes[3])
    
    # Get the tolerance from the last color
    tolerance_color = selected_colors[-1]
    tolerance_percentage = tolerance_map[tolerance_color]
    
    # Calculate tolerance range
    tolerance_value = resistor_value * (tolerance_percentage / 100)
    min_value = round(resistor_value - tolerance_value, 2)
    max_value = round(resistor_value + tolerance_value, 2)
    
    return resistor_value, tolerance_percentage, min_value, max_value

def on_calculate():
    num_bands = int(bands_combobox.get())
    selected_colors = [color_vars[i].get() for i in range(num_bands)]
    resistor_value, tolerance_percentage, min_value, max_value = calculate_resistor(num_bands, selected_colors)
    
    # Update result label
    result_label.config(text=f"电阻值: {resistor_value} 欧姆 (±{tolerance_percentage}%), 范围: {min_value} 欧姆 - {max_value} 欧姆")
    
    # Clear color display frame
    for widget in color_display_frame.winfo_children():
        widget.destroy()

    # Display color squares
    for color in selected_colors:
        hex_color = rgb_to_hex(color)
        color_box = tk.Label(color_display_frame, bg=hex_color, width=3, height=2)
        color_box.pack(side=tk.LEFT, padx=5)

def on_reset():
    bands_combobox.set("4")
    for color_var in color_vars:
        color_var.set("黑")  # Default to black
    result_label.config(text="")
    
    # Clear color display frame
    for widget in color_display_frame.winfo_children():
        widget.destroy()

def update_color_comboboxes(event):
    num_bands = int(bands_combobox.get())
    for i in range(6):
        if i < num_bands:
            color_comboboxes[i].config(state="normal")
        else:
            color_comboboxes[i].config(state="disabled")

# Create main window
root = tk.Tk()
root.title("色环电阻计算器")
root.geometry("400x460")  # Set window size

# Ring number selection
bands_label = tk.Label(root, text="选择色环数量:")
bands_label.pack()

bands_combobox = ttk.Combobox(root, values=["4", "5", "6"])
bands_combobox.set("4")
bands_combobox.pack()
bands_combobox.bind("<<ComboboxSelected>>", update_color_comboboxes)

# Color selection
colors = ["黑", "棕", "红", "橙", "黄", "绿", "蓝", "紫", "灰", "白", "金", "银"]
color_vars = []
color_comboboxes = []
for i in range(6):  # Allow up to 6 colors
    color_var = tk.StringVar(value="黑")  # Default to black
    color_vars.append(color_var)

    label = tk.Label(root, text=f"选择第 {i + 1} 条颜色:")
    label.pack()
    
    color_combobox = ttk.Combobox(root, textvariable=color_var, values=colors)
    color_combobox.set("黑")  # Default to black
    color_combobox.pack()
    color_comboboxes.append(color_combobox)

# Hide excess color selection boxes
update_color_comboboxes(None)

# Calculate and reset buttons
button_frame = tk.Frame(root)
button_frame.pack(pady=10)

calculate_button = tk.Button(button_frame, text="计算", command=on_calculate)
calculate_button.pack(side=tk.LEFT, padx=10)

reset_button = tk.Button(button_frame, text="复位", command=on_reset)
reset_button.pack(side=tk.LEFT, padx=10)

# Result display
result_label = tk.Label(root, text="")
result_label.pack(pady=10)

# Color display frame
color_display_frame = tk.Frame(root)
color_display_frame.pack(pady=10)

# Start main loop
root.mainloop()

免费评分

参与人数 4吾爱币 +10 热心值 +3 收起 理由
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
q7505413 + 1 + 1 用心讨论,共获提升!
快乐的小驹 + 1 谢谢@Thanks!
Henglie + 1 + 1 用心讨论,共获提升!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| vocan 发表于 2024-9-25 10:07
[HTML] 纯文本查看 复制代码
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>色环电阻计算器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .color-box {
            display: inline-block;
            width: 50px;
            height: 50px;
            margin: 5px;
            border: 1px solid #000;
        }
        #colorInputs {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <h1>色环电阻计算器</h1>
     
    <label for="num_bands">选择色环数量:</label>
    <select id="num_bands" onchange="updateColorInputs()">
        <option value="4">四色环</option>
        <option value="5">五色环</option>
        <option value="6">六色环</option>
    </select>
     
    <div id="colorInputs">
        <label>选择颜色:</label>
        <div id="colorInputFields"></div>
    </div>
     
    <button type="button" onclick="calculateResistor()">计算</button>
     
    <h2>计算结果:</h2>
    <p id="result"></p>
    <div id="colorBlocks"></div>
 
    <script>
        const colorMap = {
            "黑": 0, "棕": 1, "红": 2, "橙": 3,
            "黄": 4, "绿": 5, "蓝": 6, "紫": 7,
            "灰": 8, "白": 9, "金": 0, "银": 0
        };
 
        const toleranceMap = {
            "黑": 0, "棕": 1, "红": 2, "橙": 3,
            "黄": 4, "绿": 0.5, "蓝": 0.25, "紫": 0.1,
            "灰": 0.05, "白": 0, "金": 5, "银": 10
        };

        function updateColorInputs() {
            const numBands = document.getElementById('num_bands').value;
            const colorInputFields = document.getElementById('colorInputFields');
            colorInputFields.innerHTML = ''; // 清空已有输入框
            for (let i = 0; i < numBands; i++) {
                addColorInput();
            }
        }
 
        function addColorInput() {
            const colorInputFields = document.getElementById('colorInputFields');
            const select = document.createElement('select');
            select.name = 'colors';
            const colors = Object.keys(colorMap);
            colors.forEach(function(color) {
                const option = document.createElement('option');
                option.value = color;
                option.text = color;
                select.appendChild(option);
            });
            colorInputFields.appendChild(select);
        }
 
        function calculateResistor() {
            const numBands = document.getElementById('num_bands').value;
            const colorInputs = document.querySelectorAll('#colorInputFields select');
            const colorCodes = Array.prototype.map.call(colorInputs, function(select) {
                return colorMap[select.value];
            });
            const toleranceColor = colorInputs[colorInputs.length - 1].value; // 最后一条颜色表示误差
            const tolerancePercentage = toleranceMap[toleranceColor]; // 获取误差百分比
 
            let resistorValue;
            if (numBands == 4) {
                resistorValue = (colorCodes[0] * 10 + colorCodes[1]) * Math.pow(10, colorCodes[2]);
            } else if (numBands == 5 || numBands == 6) {
                resistorValue = (colorCodes[0] * 100 + colorCodes[1] * 10 + colorCodes[2]) * Math.pow(10, colorCodes[3]);
            }
 
            const toleranceValue = resistorValue * (tolerancePercentage / 100);
            const minValue = (resistorValue - toleranceValue).toFixed(2);
            const maxValue = (resistorValue + toleranceValue).toFixed(2);
 
            document.getElementById('result').innerText = resistorValue + ' 欧姆 (±' + tolerancePercentage + '%) , 取值范围: ' + minValue + ' 欧姆 - ' + maxValue + ' 欧姆';
            displayColorBlocks(colorInputs);
        }
 
        function displayColorBlocks(colorInputs) {
            const colorBlocks = document.getElementById('colorBlocks');
            colorBlocks.innerHTML = ''; // 清空之前的颜色块
            Array.prototype.forEach.call(colorInputs, function(select) {
                const color = select.value;
                const colorBox = document.createElement('div');
                colorBox.className = 'color-box';
                colorBox.style.backgroundColor = getColorHex(color);
                colorBlocks.appendChild(colorBox);
            });
        }
 
        function getColorHex(color) {
            switch (color) {
                case "黑": return "#000000";
                case "棕": return "#964B00";
                case "红": return "#FF0000";
                case "橙": return "#FFA500";
                case "黄": return "#FFFF00";
                case "绿": return "#008000";
                case "蓝": return "#0000FF";
                case "紫": return "#800080";
                case "灰": return "#808080";
                case "白": return "#FFFFFF";
                case "金": return "#FFD700";
                case "银": return "#C0C0C0";
                default: return "#FFFFFF";
            }
        }
 
        // 初始化时根据选择的色环数量生成输入框
        window.onload = function() {
            updateColorInputs();
        };
    </script>
</body>
</html>

改进后的代码,在win7平台IE11下已测试,弹出的控件运行提示要点允许阻止的内容

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
木水车 + 1 + 1 谢谢@Thanks!

查看全部评分

bgwu666 发表于 2024-9-25 00:10
其实色环电阻计算器网上已经很多了,无论是软件版本还是网页在线版都已经没什么新意了,如果楼主有兴趣的话,研究一下利用机器视觉或者机器学习自动识别色环电阻阻值应该会很有搞头
hbe 发表于 2024-9-24 21:29
lswdla 发表于 2024-9-24 21:37
第一行报错,不能运行咋办?
 楼主| vocan 发表于 2024-9-24 22:39
lswdla 发表于 2024-9-24 21:37
第一行报错,不能运行咋办?

你装了tkinter这个GUI模块吗
 楼主| vocan 发表于 2024-9-25 00:51
不过用来识别电阻这意义也不大呀,可以用开源的OpenCV库来处理图像。现在视觉识别这些很成熟了
vev 发表于 2024-9-25 07:11
有这个就方便多了
wosn 发表于 2024-9-25 07:35
感谢分享
amansbj 发表于 2024-9-25 08:34
网页版测试结果
1. 色环无法更改:只有四色环,更改为五色环、六色环后,选择颜色那里还是四个颜色
2.更改完颜色后点击计算没有任何计算结果显示
xmp788 发表于 2024-9-25 09:14
amansbj 发表于 2024-9-25 08:34
网页版测试结果
1. 色环无法更改:只有四色环,更改为五色环、六色环后,选择颜色那里还是四个颜色
2.更 ...

建议程序设计成响应式,体验会更好,触发响应式,很呆板
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-12-12 13:35

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表