欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > 【打造个性化程序启动器:使用Python和Tkinter创建一个美观的网格界面】

【打造个性化程序启动器:使用Python和Tkinter创建一个美观的网格界面】

2024/10/24 12:30:43 来源:https://blog.csdn.net/qq_42206726/article/details/141114734  浏览:    关键词:【打造个性化程序启动器:使用Python和Tkinter创建一个美观的网格界面】

当我们日常使用电脑时,经常会遇到各种程序和脚本文件需要快速启动的场景。你是否也曾想过,拥有一个可以一键启动常用程序的工具呢?今天,我们将通过Python和Tkinter库创建一个个性化的程序启动器。这个启动器不仅可以在网格中添加常用的.exe或.bat文件,还能做到下次启动时自动保存,最重要的是,它美观且易用!

为何选择Python和Tkinter?

Python因其简洁、高效的编程风格广受欢迎,而Tkinter作为其内置的图形界面库,让我们能够轻松地创建桌面应用程序。无论你是编程新手还是经验丰富的开发者,使用Tkinter都能帮助你迅速实现想法。

项目预览:我们的目标

我们将构建一个10x20的网格界面,每个网格单元代表一个可以添加程序的按钮。当你单击一个网格时,可以选择一个程序文件添加进去;再次单击时,该程序将会直接运行。更妙的是,这些设置都会被保存下来,即使你关闭程序再打开,也不会丢失。

除此之外,我们还为每个网格添加了行号和列号,方便你快速定位和查找。

代码实现:让我们动手吧!

首先,让我们看看代码是如何实现的。以下是完整的实现代码:
版本3.0

import tkinter as tk
from tkinter import filedialog
import json
import os
import subprocess
from datetime import datetime
import threading
import platform# 保存和加载文件的路径
SAVE_FILE = 'grid_programs.json'# 创建日志文件路径
log_filename = datetime.now().strftime('%Y-%m-%d') + '.txt'
log_filepath = os.path.join(os.getcwd(), log_filename)# 将字典的键从元组转换为字符串
def tuple_to_string(programs):return {f"{k[0]},{k[1]}": v for k, v in programs.items()}# 将字典的键从字符串转换回元组
def string_to_tuple(programs):return {tuple(map(int, k.split(','))): v for k, v in programs.items()}# 创建保存数据的结构
def save_programs(programs):with open(SAVE_FILE, 'w') as f:json.dump(tuple_to_string(programs), f)# 加载已保存的数据
def load_programs():if os.path.exists(SAVE_FILE):try:with open(SAVE_FILE, 'r') as f:return string_to_tuple(json.load(f))except json.JSONDecodeError:print("Error decoding JSON, starting with an empty grid.")return {}return {}# 记录操作日志
def log_operation(operation):with open(log_filepath, 'a') as log_file:log_file.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {operation}\n")# 捕获命令输出并记录到日志文件中
def execute_and_log(command):try:process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)for line in iter(process.stdout.readline, ''):log_operation(f"Command: {command}\nOutput:\n{line.strip()}")process.stdout.close()process.stderr.close()except Exception as e:log_operation(f"Failed to execute command: {command}\nError: {e}")# 在新线程中运行命令,避免阻塞主线程
def handle_program(row, col):if (row, col) in programs:# 运行已保存的程序log_operation(f"Running program from Row {row+1}, Col {col+1}: {programs[(row, col)]}")threading.Thread(target=execute_and_log, args=(programs[(row, col)],)).start()else:# 选择新文件file_path = filedialog.askopenfilename(filetypes=[("Executable files", "*.exe *.bat")])if file_path:programs[(row, col)] = file_pathbuttons[row][col].config(text=os.path.basename(file_path))save_programs(programs)log_operation(f"Added program to Row {row+1}, Col {col+1}: {file_path}")# 打开程序所在文件夹
def open_file_location(file_path):try:if platform.system() == "Windows":# 确保路径使用双反斜杠或在路径字符串前加上 r 以避免转义字符问题normalized_path = os.path.normpath(file_path)subprocess

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com