当前位置:   article > 正文

python入门学习小工具制作系列各种小工具整理_python小工具制作

python小工具制作

一、制作基于windows系统批量重命名文件小工具

参考博客:

使用python做一个批量重命名文件的小工具_讷言丶的博客-CSDN博客

效果展示:

临时01

代码实现:

  1. import os
  2. from tkinter import filedialog
  3. import tkinter as tk
  4. from tkinter import messagebox
  5. root = tk.Tk()
  6. root.geometry('400x200+550+200')
  7. root.title('批量重命名文件小工具')
  8. page = tk.Frame()
  9. page.pack()
  10. text = tk.StringVar()
  11. def rename_file():
  12. filepath = filedialog.askdirectory()
  13. index = 0
  14. if len(os.listdir(filepath)) == 0:
  15. messagebox.showinfo(title="文件重命名", message="该目录下文件为空,请重新选择目录")
  16. else:
  17. for filename in os.listdir(filepath):
  18. index += 1
  19. file_path = os.path.join(filepath, filename)
  20. if os.path.isfile(file_path):
  21. name, ext = os.path.splitext(filename)
  22. new_name = text.get() + str(index) + ext
  23. # print(new_name)
  24. os.rename(file_path, os.path.join(filepath, new_name))
  25. messagebox.showinfo(title='文件重命名', message='文件重命名成功,请查看目录')
  26. tk.Label(page).grid(row=0, column=1)
  27. tk.Label(page, text='文件名称前缀:', font=('华文楷体', 15)).grid(row=2, column=1, pady=10)
  28. tk.Entry(page, textvariable=text).grid(row=2, column=2)
  29. tk.Button(page, text='选择目录并重命名文件', font=('华文楷体', 15), command=rename_file).grid(row=3, column=2)
  30. root.mainloop()

二、制作时间戳转换器

效果展示:

临时03

代码实现:

  1. import time
  2. import tkinter as tk
  3. from tkinter import messagebox
  4. root = tk.Tk()
  5. root.geometry('400x300+500+300')
  6. root.title('时间戳转换工具')
  7. usertime = tk.StringVar()
  8. usertimestamp = tk.StringVar()
  9. page = tk.Frame(root)
  10. page.pack()
  11. tk.Label(page).grid(row=0, column=1)
  12. tk.Label(page, text='请输入时间【格式:Y-M-D h:m:s】:', font=('黑体', 10)).grid(row=1, column=1, pady=10)
  13. tk.Entry(page, textvariable=usertime).grid(row=1, column=2)
  14. tk.Label(page, text='请输入时间戳: ', font=('黑体', 10)).grid(row=3, column=1, pady=30)
  15. tk.Entry(page, textvariable=usertimestamp).grid(row=3, column=2)
  16. # 将时间转换为时间戳,秒级
  17. def timestamp_s():
  18. time_value = usertime.get()
  19. timeArray = time.strptime(time_value, "%Y-%m-%d %H:%M:%S")
  20. timestamp = time.mktime(timeArray)
  21. times = int(timestamp)
  22. messagebox.showinfo(title='时间戳(s)', message=f'获取到的时间戳(s)为{times}')
  23. # 将时间转换为时间戳,毫秒级
  24. def timestamp_ms():
  25. time_value = usertime.get()
  26. timeArray = time.strptime(time_value, "%Y-%m-%d %H:%M:%S")
  27. timestamp = time.mktime(timeArray)
  28. times = int(round(timestamp * 1000))
  29. messagebox.showinfo(title='时间戳(s)', message=f'获取到的时间戳(s)为{times}')
  30. # 秒级时间戳转换
  31. def time_s():
  32. time_value = usertimestamp.get()
  33. if len(time_value) == 10:
  34. timeas = int(time_value)
  35. time_local = time.localtime(timeas)
  36. dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
  37. messagebox.showinfo(title='时间', message=f'获取到的时间为{dt}')
  38. elif len(time_value) == 13:
  39. timeas = int(time_value)
  40. timestamps = int(round(timeas / 1000))
  41. time_local = time.localtime(timestamps)
  42. dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
  43. messagebox.showinfo(title='时间', message=f'获取到的时间为{dt}')
  44. tk.Button(page, text='转换为时间戳(s)', command=timestamp_s).grid(row=2, column=1)
  45. tk.Button(page, text='转换为时间戳(ms)', command=timestamp_ms).grid(row=2, column=2)
  46. tk.Button(page, text='转换为时间', command=time_s).grid(row=4, column=1)
  47. root.mainloop()

三、制作图书管理小工具

效果展示:

临时02

代码实现:

  1. import tkinter as tk
  2. from tkinter import messagebox
  3. # 定义Book类
  4. class Book:
  5. def __init__(self, title, author, isbn):
  6. self.title = title
  7. self.author = author
  8. self.isbn = isbn
  9. # 定义GUI窗口
  10. class BookManagementSystem:
  11. def __init__(self, master):
  12. self.master = master
  13. self.master.title("图书管理系统")
  14. # 创建标题标签
  15. tk.Label(self.master, text="图书管理系统", font=("Arial", 20)).grid(column=0, row=0, columnspan=3, pady=10)
  16. # 创建书籍信息输入框
  17. tk.Label(self.master, text="书名").grid(column=0, row=1)
  18. self.title_entry = tk.Entry(self.master)
  19. self.title_entry.grid(column=1, row=1, padx=5, pady=5)
  20. tk.Label(self.master, text="作者").grid(column=0, row=2)
  21. self.author_entry = tk.Entry(self.master)
  22. self.author_entry.grid(column=1, row=2, padx=5, pady=5)
  23. tk.Label(self.master, text="ISBN号").grid(column=0, row=3)
  24. self.isbn_entry = tk.Entry(self.master)
  25. self.isbn_entry.grid(column=1, row=3, padx=5, pady=5)
  26. # 创建添加书籍按钮
  27. self.add_book_button = tk.Button(self.master, text="添加书籍", command=self.add_book)
  28. self.add_book_button.grid(column=0, row=4, pady=10)
  29. # 创建书籍列表框
  30. tk.Label(self.master, text="当前书籍列表").grid(column=2, row=1)
  31. self.book_listbox = tk.Listbox(self.master)
  32. self.book_listbox.grid(column=2, row=2, rowspan=3, padx=10, pady=5)
  33. self.update_book_list()
  34. # 创建删除书籍按钮
  35. self.delete_book_button = tk.Button(self.master, text="删除书籍", command=self.delete_book)
  36. self.delete_book_button.grid(column=2, row=4, pady=10)
  37. # 添加书籍方法
  38. def add_book(self):
  39. title = self.title_entry.get()
  40. author = self.author_entry.get()
  41. isbn = self.isbn_entry.get()
  42. book = Book(title, author, isbn)
  43. with open("books.txt", "a") as f:
  44. f.write(f"{book.title},{book.author},{book.isbn}\n")
  45. messagebox.showinfo("添加书籍", "添加书籍成功!")
  46. self.update_book_list()
  47. # 删除书籍方法
  48. def delete_book(self):
  49. selection = self.book_listbox.curselection()
  50. if len(selection) == 0:
  51. messagebox.showerror("删除书籍", "请选择要删除的书籍!")
  52. return
  53. index = selection[0]
  54. book = self.book_listbox.get(index)
  55. with open("books.txt", "r") as f:
  56. lines = f.readlines()
  57. with open("books.txt", "w") as f:
  58. for line in lines:
  59. if line.strip() != book:
  60. f.write(line)
  61. messagebox.showinfo("删除书籍", "删除书籍成功!")
  62. self.update_book_list()
  63. # 更新书籍列表方法
  64. def update_book_list(self):
  65. self.book_listbox.delete(0, tk.END)
  66. with open("books.txt", "r") as f:
  67. for line in f.readlines():
  68. book = line.strip()
  69. self.book_listbox.insert(tk.END, book)
  70. # 启动GUI窗口
  71. if __name__ == '__main__':
  72. root = tk.Tk()
  73. app = BookManagementSystem(root)
  74. root.mainloop()

四、制作jpg、png图片转ico图标小工具

效果展示:

临时04

代码实现:

  1. import tkinter as tk
  2. from tkinter import filedialog
  3. # PythonMargick包可以到Unofficial Windows Binaries for Python Extension Packages下载
  4. import PythonMagick
  5. root = tk.Tk()
  6. root.withdraw()
  7. Fpath = filedialog.askopenfilename()
  8. img = PythonMagick.Image(Fpath)
  9. # 这里要设置一下尺寸,不然会报ico尺寸异常错误
  10. img.sample('256x256')
  11. img.write('robin.ico')

五、制作图片和base64互转小工具

效果展示:

临时05

代码实现:

  1. import base64
  2. import tkinter as tk
  3. from tkinter import filedialog
  4. root = tk.Tk()
  5. root.withdraw()
  6. Fpath = filedialog.askopenfilename()
  7. def file_to_base64():
  8. print(Fpath)
  9. f=open(Fpath,'rb') #二进制方式打开图文件
  10. ls_f=base64.b64encode(f.read()) #读取文件内容,转换为base64编码
  11. open('x.txt', 'wb').write(ls_f)
  12. def base64_to_file():
  13. print(Fpath)
  14. decoded = base64.b64decode(open(Fpath, 'rb').read())
  15. open('1.jpg', 'wb').write(decoded) # 保存
  16. if __name__ == '__main__':
  17. if "jpg" in Fpath or 'png' in Fpath or 'jpeg' in Fpath:
  18. file_to_base64()
  19. elif 'txt' in Fpath:
  20. base64_to_file()

六、制作英文翻译器(小工具)

代码逻辑:

        requests模块请求第三方翻译接口,拿到数据后通过tkinter展示出来

效果展示:

临时06

代码实现:

  1. import requests
  2. import tkinter as tk
  3. from tkinter import messagebox
  4. root = tk.Tk()
  5. root.geometry('1000x500+350+100')
  6. root.title('英文翻译器')
  7. page = tk.Frame()
  8. page.pack()
  9. text = tk.StringVar()
  10. tk.Label(page).grid(row=0, column=1)
  11. tk.Label(page, text='翻译小程序', font=('黑体', 20)).grid(row=1, column=1, pady=20)
  12. def sure():
  13. page.pack_forget()
  14. page2.pack()
  15. def exit():
  16. page2.pack_forget()
  17. page.pack()
  18. def dcfy():
  19. url = 'https://fanyi.xxx.com/trans'
  20. headers = {
  21. "user-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
  22. "referer": 'https://fanyi.xxx.com/'
  23. }
  24. chinese = text.get()
  25. data = {
  26. 'q': chinese,
  27. 'from': 'Auto',
  28. 'to': 'Auto'
  29. }
  30. resp = requests.post(url=url, headers=headers, data=data).json()
  31. chinatext = resp.get('web')[0]['key']
  32. Englishtext = resp.get('web')[0]['value'][0]
  33. messagebox.showinfo(title='单词翻译', message=Englishtext)
  34. def para():
  35. page.pack_forget()
  36. page3.pack()
  37. def exit2():
  38. page3.pack_forget()
  39. page.pack()
  40. def dlfy():
  41. url = 'https://fanyi.xxx.com/trans'
  42. headers = {
  43. "user-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
  44. "referer": 'https://fanyi.xxx.com/'
  45. }
  46. chinese = text.get()
  47. data = {
  48. 'q': chinese,
  49. 'from': 'Auto',
  50. 'to': 'Auto'
  51. }
  52. resp = requests.post(url=url, headers=headers, data=data).json()
  53. Englishtext = resp['translation'][0]
  54. messagebox.showinfo(title='段落句子翻译', message=f'{Englishtext}')
  55. tk.Button(page, text='单词翻译', font=('黑体', 15), command=sure).grid(row=2, column=1, pady=20)
  56. tk.Button(page, text='句子翻译', font=('黑体', 15), command=para).grid(row=2, column=2, padx=10, pady=20)
  57. page2 = tk.Frame()
  58. tk.Entry(page2, textvariable=text, bd=5).grid(row=2, column=2, pady=20)
  59. tk.Button(page2, text='翻译', font=('黑体', 15), command=dcfy).grid(row=3, column=1, padx=20)
  60. tk.Button(page2, text='返回上一页', font=('黑体', 15), command=exit).grid(row=3, column=2, pady=20)
  61. page3 = tk.Frame()
  62. tk.Entry(page3, textvariable=text, bd=5).grid(row=2, column=2, pady=20)
  63. tk.Button(page3, text='翻译', font=('黑体', 15), command=dlfy).grid(row=3, column=1, padx=20)
  64. tk.Button(page3, text='返回上一页', font=('黑体', 15), command=exit2).grid(row=3, column=2, pady=20)
  65. root.mainloop()

七、制作图片查看器(小工具):

效果展示:

临时07

代码实现:

  1. import tkinter as tk
  2. import glob
  3. from PIL import Image, ImageTk
  4. root = tk.Tk() # 创建窗口
  5. root.geometry('650x700+300+50') # 设置弹出窗口的大小和在屏幕中的位置
  6. root.title('图片查看器') # 设置弹出窗口的标题
  7. imgs = glob.glob('img/*.jpeg')
  8. imgs = [ImageTk.PhotoImage(Image.open(item)) for item in imgs]
  9. current_photo_no = 0
  10. img_label = tk.Label(root, image=imgs[current_photo_no], width=640, height=640)
  11. img_label.pack()
  12. number_var = tk.StringVar()
  13. number_var.set('1 of 8')
  14. tk.Label(root, textvariable=number_var, bd=1, relief=tk.SUNKEN, anchor=tk.CENTER).pack(fill=tk.X)
  15. button_form = tk.Frame(root)
  16. button_form.pack()
  17. prev_img = tk.Button(button_form, text='上一页')
  18. next_img = tk.Button(button_form, text='下一页')
  19. prev_img.pack(side=tk.LEFT, anchor=tk.CENTER)
  20. next_img.pack(side=tk.RIGHT, anchor=tk.CENTER)
  21. def change_images(next_no):
  22. global current_photo_no
  23. current_photo_no += next_no
  24. if current_photo_no >= len(imgs):
  25. current_photo_no = 0
  26. if current_photo_no < 0:
  27. current_photo_no = len(imgs) - 1
  28. number_var.set(f'{current_photo_no + 1} of {len(imgs)}')
  29. img_label.configure(image=imgs[current_photo_no])
  30. prev_img.config(command=lambda: change_images(-1))
  31. next_img.config(command=lambda: change_images(1))
  32. root.mainloop()

八、制作BMI身体指数计算器(小工具):

效果展示:

临时08

代码实现:

  1. import tkinter as tk
  2. from tkinter import messagebox
  3. root = tk.Tk()
  4. root.geometry('350x230+500+230') # 设置弹出框位置和大小
  5. # root.iconbitmap('E:/pythonProject/3.ico') # 设置弹出框图标
  6. root.title('BMI身体指数计算器')
  7. height = tk.DoubleVar()
  8. weight = tk.DoubleVar()
  9. page = tk.Frame(root)
  10. page.pack()
  11. tk.Label(page).grid(row=0, column=0)
  12. tk.Label(page, text='身高(米): ').grid(row=2, column=1, pady=20)
  13. tk.Entry(page, textvariable=height).grid(row=2, column=2)
  14. tk.Label(page, text='体重(kg): ').grid(row=3, column=1, pady=20)
  15. tk.Entry(page, textvariable=weight).grid(row=3, column=2)
  16. def jisuan():
  17. shengao = height.get()
  18. tizhong = weight.get()
  19. # print(shengao,tizhong)
  20. if shengao > 0 and tizhong > 0:
  21. BMI = tizhong / shengao ** 2
  22. BMI_new = float(('%.2f' % BMI))
  23. messagebox.showinfo(title='BMI身体指数计算',
  24. message=f'您的身高为{shengao}m,您的体重为{tizhong}kg,您的BMI身体指数为{BMI_new}')
  25. if BMI_new < 18.4:
  26. messagebox.showinfo(title='BMI身体指数计算', message='BMI指数较低,提示您的身体消瘦,要注意补充营养哦!')
  27. elif BMI_new > 18.5 and BMI_new < 24:
  28. messagebox.showinfo(title='BMI身体指数计算', message='BMI指数为正常值,继续加油!')
  29. elif BMI_new > 24 and BMI_new < 28:
  30. messagebox.showinfo(title='BMI身体指数计算',
  31. message='BMI指数较高,属于是超重了,提示您需要合理饮食,加强锻炼哦!')
  32. elif BMI_new > 28:
  33. messagebox.showinfo(title='BMI身体指数计算',
  34. message='BMI指数很高,属于肥胖了,提示您需要注意身体健康了,过胖会增加人体器官的负担哦!')
  35. tk.Button(page, text='计算', command=jisuan).grid(row=4, column=2, pady=10)
  36. root.mainloop()

九,制作json数据格式化小工具

小工具效果:对于json格式(混乱)的数据做规范修改,格式化输出json数据。

  1. import json
  2. import tkinter as tk
  3. from tkinter import filedialog
  4. root = tk.Tk()
  5. root.withdraw()
  6. json_data_path = filedialog.askopenfilename()
  7. with open(json_data_path) as json_file:
  8. data = json.load(json_file)
  9. formatted_data = json.dumps(data, indent=4, sort_keys=True)
  10. with open(json_data_path, 'w') as fp:
  11. fp.write(formatted_data)

十,微信消息轰炸

代码逻辑:即通过python的pyautogui库定位到微信的像素位置,然后通过模拟鼠标键盘操作自动发送消息

实现步骤:

1)先通过pyautogui定位到微信的桌面位置。

  1. import pyautogui
  2. import time
  3. def search_positon():
  4. time.sleep(1)
  5. x1,y1 = pyautogui.position()
  6. print('您当前的位置坐标为:','x:'+str(x1)+'','y:'+str(y1))
  7. if __name__ == '__main__':
  8. while True:
  9. search_positon()
  10. pass

效果展示:【具体方位不是固定的,只要确认可以点击打开微信即可】

2)编写消息发送逻辑,通过pyautogui自动下发微信消息

  1. import pyautogui
  2. import time
  3. import pyperclip
  4. user = input('输入用户名称:')
  5. userinput = input('输入要发送的消息:')
  6. pyautogui.click(37, 428, button='left', clicks=2)
  7. # 找到微信程序位置,打开微信程序
  8. time.sleep(0.5)
  9. # 睡眠0.5秒
  10. pyautogui.click(368, 83, button='left', clicks=1)
  11. # 点击微信搜索框,具体位置可以通过运行上面的代码定位
  12. pyperclip.copy(user)
  13. pyautogui.hotkey('Ctrl', 'v')
  14. # 输入搜索内容
  15. pyautogui.press('enter')
  16. # 点击回车搜索
  17. time.sleep(0.5)
  18. pyautogui.press('enter')
  19. while True:
  20. pyperclip.copy(userinput)
  21. pyautogui.hotkey('Ctrl', 'v')
  22. pyautogui.press('enter')
  23. time.sleep(0.5)
  24. # 死循环执行消息发送,每隔0.5秒发送一次

效果展示:

十一,制作OCR图片识别小工具

参考博客:

【Python • 图片识别】pytesseract快速识别提取图片中的文字_python识别图片中的文字_广龙宇的博客-CSDN博客利用python做图片识别,识别提取图片中的文字会有很多方法,但是想要简单一点怎么办,那就可以使用tesseract识别引擎来实现,一行代码就可以做到提取图片文本。_python识别图片中的文字https://blog.csdn.net/weixin_47754149/article/details/125651707

效果展示:

临时09

代码实现:

  1. from PIL import Image
  2. import pytesseract
  3. import tkinter as tk
  4. from tkinter import filedialog
  5. root = tk.Tk()
  6. root.withdraw()
  7. Fpath = filedialog.askopenfilename()
  8. def read_image(name):
  9. with open('视频文件.txt','w',encoding='utf-8') as fp:
  10. fp.write(pytesseract.image_to_string(Image.open(name), lang='chi_sim'))
  11. def main():
  12. read_image(Fpath)
  13. if __name__ == '__main__':
  14. reslet = main()
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/829370
推荐阅读
相关标签
  

闽ICP备14008679号