在日常开发过程中,我们经常需要进行各种琐碎但又必不可少的操作,比如文件处理、编码转换、哈希计算、二维码生成、单位换算等。如果每次都需要单独寻找工具或者编写零散的代码,效率难免会受到影响。因此,本文介绍一款基于 Python 编写的 全能工具箱,它涵盖了开发过程中常用的功能,极大地提高了工作效率。
该工具箱主要涵盖以下功能:
接下来,我们将详细介绍如何使用这些功能,并展示相关代码示例。
1.文件操作
在开发过程中,我们经常需要合并多个文件或者拆分大文件。以下是文件合并的示例代码:
1 2 3 4 5 6 7 8 |
import os
def merge_files(input_files, output_file): with open(output_file, 'wb') as outfile: for file in input_files: with open(file, 'rb') as infile: outfile.write(infile.read()) print(f'文件合并完成: {output_file}') |
使用方式:
1 |
merge_files(['file1.txt', 'file2.txt'], 'merged.txt') |
类似地,我们可以拆分大文件:
1 2 3 4 5 6 7 8 |
def split_file(input_file, chunk_size): with open(input_file, 'rb') as infile: chunk_number = 1 while chunk := infile.read(chunk_size): with open(f'{input_file}.part{chunk_number}', 'wb') as chunk_file: chunk_file.write(chunk) chunk_number += 1 print(f'文件拆分完成,共 {chunk_number - 1} 份') |
2.二维码生成与解析
Python 的 qrcode 和 pyzbar 库可以轻松处理二维码。
生成二维码
1 2 3 4 5 6 |
import qrcode
def generate_qr_code(data, output_file='qrcode.png'): qr = qrcode.make(data) qr.save(output_file) print(f'二维码已生成: {output_file}') |
解析二维码
1 2 3 4 5 6 |
from pyzbar.pyzbar import decode from PIL import Image
def decode_qr_code(image_path): data = decode(Image.open(image_path)) return data[0].data.decode(‘utf-8') if data else ‘未识别到二维码' |
3.哈希计算
计算 MD5 和 SHA256
1 2 3 4 5 6 7 8 |
import hashlib
def calculate_hash(file_path, hash_type='md5'): hash_func = hashlib.md5() if hash_type == 'md5' else hashlib.sha256() with open(file_path, 'rb') as f: while chunk := f.read(4096): hash_func.update(chunk) return hash_func.hexdigest() |
示例:
1 |
print(calculate_hash('example.txt', 'sha256')) |
4.时间戳转换
时间戳转日期
1 2 3 4 |
from datetime import datetime
???????def timestamp_to_date(timestamp): return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') |
日期转时间戳
1 2 |
def date_to_timestamp(date_str): return int(datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').timestamp()) |
5.IP 归属地查询
查询 IP 归属地(基于 API)
1 2 3 4 5 6 |
import requests
def get_ip_location(ip): url = f'https://ipinfo.io/{ip}/json' response = requests.get(url) return response.json() if response.status_code == 200 else '查询失败' |
示例:
1 |
print(get_ip_location('8.8.8.8')) |
6.单位换算
文件大小转换
1 2 3 4 5 6 7 |
def human_readable_size(size_bytes): units = ['B', 'KB', 'MB', 'GB', 'TB'] i = 0 while size_bytes >= 1024 and i < len(units) - 1: size_bytes /= 1024.0 i += 1 return f'{size_bytes:.2f} {units[i]}' |
示例:
1 |
print(human_readable_size(1048576)) # 1.00 MB |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
import tkinter as tk from tkinter import ttk, filedialog, messagebox import base64 import hashlib import os import qrcode import webbrowser import time import random import json import requests from PIL import Image, ImageTk from datetime import datetime from tkinter import scrolledtext import pyperclip import zhconv
class ToolBox: def __init__(self, root): self.root = root self.root.title("超级工具箱 v2.0") self.root.geometry("1000x800")
# 创建标签容器 self.notebook = ttk.Notebook(root) self.notebook.pack(fill='both', expand=True)
# 创建各个功能标签页 self.create_file_tools_tab() self.create_encoder_tab() self.create_qrcode_tab() self.create_hash_tools_tab() self.create_time_tools_tab() self.create_network_tools_tab() self.create_conversion_tools_tab() self.create_other_tools_tab()
# 添加右键菜单 self.create_context_menu()
# 右键菜单功能 def create_context_menu(self): self.context_menu = tk.Menu(self.root, tearoff=0) self.context_menu.add_command(label="复制", command=self.copy_text) self.context_menu.add_command(label="粘贴", command=self.paste_text)
# 绑定右键事件 self.root.bind("<Button-3>", self.show_context_menu)
def show_context_menu(self, event): self.context_menu.post(event.x_root, event.y_root)
def copy_text(self): widget = self.root.focus_get() if isinstance(widget, tk.Entry): widget.event_generate("<<Copy>>") elif isinstance(widget, tk.Text): widget.event_generate("<<Copy>>")
def paste_text(self): widget = self.root.focus_get() if isinstance(widget, tk.Entry): widget.event_generate("<<Paste>>") elif isinstance(widget, tk.Text): widget.event_generate("<<Paste>>")
# 以下是各功能标签页的创建和功能实现 def create_file_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="文件工具")
# 文件搜索功能 search_frame = ttk.LabelFrame(tab, text="文件搜索") search_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(search_frame, text="搜索目录:").grid(row=0, column=0, sticky='w') self.path_entry = ttk.Entry(search_frame, width=50) self.path_entry.grid(row=0, column=1, padx=5)
ttk.Button(search_frame, text="选择目录", command=self.browse_directory).grid(row=0, column=2)
ttk.Label(search_frame, text="关键词:").grid(row=1, column=0, sticky='w') self.keyword_entry = ttk.Entry(search_frame, width=50) self.keyword_entry.grid(row=1, column=1, pady=5)
ttk.Button(search_frame, text="开始搜索", command=self.search_files).grid(row=2, column=1, pady=10)
self.result_text = scrolledtext.ScrolledText(search_frame, height=10, width=80) self.result_text.grid(row=3, column=0, columnspan=3)
# 文件批量重命名 rename_frame = ttk.LabelFrame(tab, text="批量重命名") rename_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(rename_frame, text="原文件名:").grid(row=0, column=0) self.original_name = ttk.Entry(rename_frame, width=25) self.original_name.grid(row=0, column=1)
ttk.Label(rename_frame, text="新文件名:").grid(row=0, column=2) self.new_name = ttk.Entry(rename_frame, width=25) self.new_name.grid(row=0, column=3)
ttk.Button(rename_frame, text="执行重命名", command=self.batch_rename).grid(row=0, column=4, padx=10)
def create_encoder_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="编解码工具")
# Base64 编解码 base64_frame = ttk.LabelFrame(tab, text="Base64 编解码") base64_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(base64_frame, text="输入内容:").grid(row=0, column=0) self.base64_input = scrolledtext.ScrolledText(base64_frame, height=5, width=40) self.base64_input.grid(row=0, column=1, padx=5)
btn_frame = ttk.Frame(base64_frame) btn_frame.grid(row=1, column=1, pady=5) ttk.Button(btn_frame, text="编码", command=self.base64_encode).pack(side='left', padx=5) ttk.Button(btn_frame, text="解码", command=self.base64_decode).pack(side='left', padx=5) ttk.Button(btn_frame, text="清空", command=self.clear_base64).pack(side='right', padx=5)
ttk.Label(base64_frame, text="结果:").grid(row=2, column=0) self.base64_output = scrolledtext.ScrolledText(base64_frame, height=5, width=40) self.base64_output.grid(row=2, column=1, padx=5)
# URL 编解码 url_frame = ttk.LabelFrame(tab, text="URL 编解码") url_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(url_frame, text="URL:").grid(row=0, column=0) self.url_entry = ttk.Entry(url_frame, width=50) self.url_entry.grid(row=0, column=1, padx=5)
btn_frame = ttk.Frame(url_frame) btn_frame.grid(row=1, column=1, pady=5) ttk.Button(btn_frame, text="编码", command=self.url_encode).pack(side='left', padx=5) ttk.Button(btn_frame, text="解码", command=self.url_decode).pack(side='left', padx=5)
def create_qrcode_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="二维码工具")
frame = ttk.LabelFrame(tab, text="二维码生成器") frame.pack(padx=10, pady=10, fill='both', expand=True)
ttk.Label(frame, text="输入内容:").grid(row=0, column=0) self.qr_content = ttk.Entry(frame, width=60) self.qr_content.grid(row=0, column=1, padx=5)
ttk.Button(frame, text="生成二维码", command=self.generate_qrcode).grid(row=1, column=1, pady=5) ttk.Button(frame, text="保存二维码", command=self.save_qrcode).grid(row=1, column=0, pady=5)
self.qr_image_label = ttk.Label(frame) self.qr_image_label.grid(row=2, column=0, columnspan=2)
def create_hash_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="哈希工具")
# 字符串哈希 str_frame = ttk.LabelFrame(tab, text="字符串哈希") str_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(str_frame, text="输入字符串:").grid(row=0, column=0) self.hash_input = ttk.Entry(str_frame, width=50) self.hash_input.grid(row=0, column=1)
ttk.Button(str_frame, text="计算哈希", command=self.calculate_str_hash).grid(row=0, column=2)
self.hash_result = ttk.Entry(str_frame, width=70) self.hash_result.grid(row=1, column=0, columnspan=3, pady=5)
# 文件哈希 file_frame = ttk.LabelFrame(tab, text="文件哈希") file_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(file_frame, text="选择文件:").grid(row=0, column=0) self.file_hash_entry = ttk.Entry(file_frame, width=50) self.file_hash_entry.grid(row=0, column=1)
ttk.Button(file_frame, text="浏览", command=self.browse_hash_file).grid(row=0, column=2) ttk.Button(file_frame, text="计算文件哈希", command=self.calculate_file_hash).grid(row=1, column=1)
def create_time_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="时间工具")
# 时间戳转换 ts_frame = ttk.LabelFrame(tab, text="时间戳转换") ts_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(ts_frame, text="时间戳:").grid(row=0, column=0) self.timestamp_entry = ttk.Entry(ts_frame) self.timestamp_entry.grid(row=0, column=1) ttk.Button(ts_frame, text="转换", command=self.timestamp_to_datetime).grid(row=0, column=2)
ttk.Label(ts_frame, text="日期时间:").grid(row=1, column=0) self.datetime_entry = ttk.Entry(ts_frame) self.datetime_entry.grid(row=1, column=1) ttk.Button(ts_frame, text="转换", command=self.datetime_to_timestamp).grid(row=1, column=2)
ttk.Button(ts_frame, text="当前时间", command=self.get_current_time).grid(row=2, column=1)
def create_network_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="网络工具")
# IP查询 ip_frame = ttk.LabelFrame(tab, text="IP地址查询") ip_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(ip_frame, text="输入IP:").grid(row=0, column=0) self.ip_entry = ttk.Entry(ip_frame, width=25) self.ip_entry.grid(row=0, column=1) ttk.Button(ip_frame, text="查询", command=self.ip_lookup).grid(row=0, column=2)
self.ip_result = scrolledtext.ScrolledText(ip_frame, height=5, width=60) self.ip_result.grid(row=1, column=0, columnspan=3)
def create_conversion_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="转换工具")
# 单位转换 unit_frame = ttk.LabelFrame(tab, text="单位转换") unit_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(unit_frame, text="数值:").grid(row=0, column=0) self.num_entry = ttk.Entry(unit_frame, width=15) self.num_entry.grid(row=0, column=1)
self.unit_from = ttk.Combobox(unit_frame, values=["米", "千米", "英尺"]) self.unit_from.grid(row=0, column=2) ttk.Label(unit_frame, text="转换为").grid(row=0, column=3) self.unit_to = ttk.Combobox(unit_frame, values=["米", "千米", "英尺"]) self.unit_to.grid(row=0, column=4)
ttk.Button(unit_frame, text="转换", command=self.unit_convert).grid(row=0, column=5) self.unit_result = ttk.Label(unit_frame, text="结果:") self.unit_result.grid(row=1, column=0, columnspan=6)
# 简繁转换 zh_frame = ttk.LabelFrame(tab, text="简繁转换") zh_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(zh_frame, text="输入文本:").grid(row=0, column=0) self.zh_input = scrolledtext.ScrolledText(zh_frame, height=3, width=30) self.zh_input.grid(row=0, column=1)
btn_frame = ttk.Frame(zh_frame) btn_frame.grid(row=1, column=1) ttk.Button(btn_frame, text="转简体", command=lambda: self.convert_zh('zh-cn')).pack(side='left') ttk.Button(btn_frame, text="转繁体", command=lambda: self.convert_zh('zh-tw')).pack(side='left')
self.zh_output = scrolledtext.ScrolledText(zh_frame, height=3, width=30) self.zh_output.grid(row=2, column=1)
def create_other_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="其他工具")
# 密码生成器 pwd_frame = ttk.LabelFrame(tab, text="随机密码生成") pwd_frame.pack(padx=10, pady=5, fill='both', expand=True)
ttk.Label(pwd_frame, text="长度:").grid(row=0, column=0) self.pwd_length = ttk.Spinbox(pwd_frame, from_=6, to=32, width=5) self.pwd_length.grid(row=0, column=1)
self.use_digits = tk.BooleanVar(value=True) ttk.Checkbutton(pwd_frame, text="包含数字", variable=self.use_digits).grid(row=0, column=2)
self.use_symbols = tk.BooleanVar(value=True) ttk.Checkbutton(pwd_frame, text="包含符号", variable=self.use_symbols).grid(row=0, column=3)
ttk.Button(pwd_frame, text="生成密码", command=self.generate_password).grid(row=0, column=4) self.password_entry = ttk.Entry(pwd_frame, width=30) self.password_entry.grid(row=1, column=0, columnspan=5, pady=5)
# 以下是各功能的实现方法 def browse_directory(self): path = filedialog.askdirectory() self.path_entry.delete(0, tk.END) self.path_entry.insert(0, path)
def search_files(self): directory = self.path_entry.get() keyword = self.keyword_entry.get()
if not directory or not keyword: messagebox.showwarning("提示", "请先选择目录并输入关键词") return
self.result_text.delete(1.0, tk.END) count = 0
for root, dirs, files in os.walk(directory): for file in files: if keyword.lower() in file.lower(): filepath = os.path.join(root, file) self.result_text.insert(tk.END, filepath + "\n") count += 1
self.result_text.insert(tk.END, f"\n找到 {count} 个匹配文件")
def batch_rename(self): original = self.original_name.get() new = self.new_name.get() directory = self.path_entry.get()
if not directory: messagebox.showwarning("提示", "请先选择目录") return
count = 0 for filename in os.listdir(directory): if original in filename: new_filename = filename.replace(original, new) os.rename( os.path.join(directory, filename), os.path.join(directory, new_filename) ) count += 1
messagebox.showinfo("完成", f"成功重命名 {count} 个文件")
def base64_encode(self): text = self.base64_input.get("1.0", tk.END).strip() encoded = base64.b64encode(text.encode()).decode() self.base64_output.delete("1.0", tk.END) self.base64_output.insert(tk.END, encoded)
def base64_decode(self): text = self.base64_input.get("1.0", tk.END).strip() try: decoded = base64.b64decode(text).decode() self.base64_output.delete("1.0", tk.END) self.base64_output.insert(tk.END, decoded) except: messagebox.showerror("错误", "解码失败,请检查输入内容")
def clear_base64(self): self.base64_input.delete("1.0", tk.END) self.base64_output.delete("1.0", tk.END)
def url_encode(self): text = self.url_entry.get() encoded = requests.utils.quote(text) self.url_entry.delete(0, tk.END) self.url_entry.insert(0, encoded)
def url_decode(self): text = self.url_entry.get() decoded = requests.utils.unquote(text) self.url_entry.delete(0, tk.END) self.url_entry.insert(0, decoded)
def generate_qrcode(self): data = self.qr_content.get() if not data: return
qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(data) qr.make(fit=True) self.qr_img = qr.make_image(fill_color="black", back_color="white") self.display_qrcode()
def display_qrcode(self): self.qr_img.save("temp_qr.png") image = Image.open("temp_qr.png") image.thumbnail((300, 300)) photo = ImageTk.PhotoImage(image) self.qr_image_label.config(image=photo) self.qr_image_label.image = photo
def save_qrcode(self): if hasattr(self, 'qr_img'): filename = filedialog.asksaveasfilename( defaultextension=".png", filetypes=[("PNG文件", "*.png"), ("所有文件", "*.*")] ) if filename: self.qr_img.save(filename) messagebox.showinfo("保存成功", "二维码已保存")
def calculate_str_hash(self): text = self.hash_input.get() algorithms = ['md5', 'sha1', 'sha256'] results = []
for algo in algorithms: hash_obj = hashlib.new(algo) hash_obj.update(text.encode()) results.append(f"{algo.upper()}: {hash_obj.hexdigest()}")
self.hash_result.delete(0, tk.END) self.hash_result.insert(0, " | ".join(results))
def browse_hash_file(self): filename = filedialog.askopenfilename() self.file_hash_entry.delete(0, tk.END) self.file_hash_entry.insert(0, filename)
def calculate_file_hash(self): filename = self.file_hash_entry.get() if not os.path.isfile(filename): return
hash_md5 = hashlib.md5() with open(filename, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk)
self.hash_result.delete(0, tk.END) self.hash_result.insert(0, f"MD5: {hash_md5.hexdigest()}")
def timestamp_to_datetime(self): try: ts = int(self.timestamp_entry.get()) dt = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') self.datetime_entry.delete(0, tk.END) self.datetime_entry.insert(0, dt) except: messagebox.showerror("错误", "无效的时间戳")
def datetime_to_timestamp(self): try: dt_str = self.datetime_entry.get() dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') ts = int(dt.timestamp()) self.timestamp_entry.delete(0, tk.END) self.timestamp_entry.insert(0, ts) except: messagebox.showerror("错误", "无效的日期格式")
def get_current_time(self): current_ts = int(time.time()) current_dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.timestamp_entry.delete(0, tk.END) self.timestamp_entry.insert(0, current_ts) self.datetime_entry.delete(0, tk.END) self.datetime_entry.insert(0, current_dt)
def ip_lookup(self): ip = self.ip_entry.get() try: response = requests.get(f"http://ip-api.com/json/{ip}") data = response.json() result = f""" 国家: {data.get('country', '未知')} 地区: {data.get('regionName', '未知')} 城市: {data.get('city', '未知')} ISP: {data.get('isp', '未知')} AS: {data.get('as', '未知')} """ self.ip_result.delete(1.0, tk.END) self.ip_result.insert(tk.END, result) except: messagebox.showerror("错误", "查询失败")
def unit_convert(self): try: value = float(self.num_entry.get()) unit_from = self.unit_from.get() unit_to = self.unit_to.get()
# 转换系数(米为基准单位) units = { "米": 1, "千米": 1000, "英尺": 0.3048 }
result = value * units[unit_from] / units[unit_to] self.unit_result.config(text=f"结果: {result:.4f} {unit_to}") except: messagebox.showerror("错误", "无效的输入")
def convert_zh(self, target): text = self.zh_input.get("1.0", tk.END) converted = zhconv.convert(text, target) self.zh_output.delete("1.0", tk.END) self.zh_output.insert(tk.END, converted)
def generate_password(self): length = int(self.pwd_length.get()) chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' if self.use_digits.get(): chars += '0123456789' if self.use_symbols.get(): chars += '!@#$%^&*()_+-='
password = ''.join(random.choice(chars) for _ in range(length)) self.password_entry.delete(0, tk.END) self.password_entry.insert(0, password) pyperclip.copy(password) messagebox.showinfo("提示", "密码已复制到剪贴板")
if __name__ == "__main__": root = tk.Tk() app = ToolBox(root) root.mainloop() |
本文介绍了如何使用 Python 实现一款 高效的全能工具箱,涵盖了文件操作、二维码处理、哈希计算、时间转换、IP 查询和单位换算等功能。此工具能够帮助开发者提高工作效率,减少重复劳动,适用于各种开发场景。