Python程序片段

主窗口标题栏左上角图标#

def set_window_icon():
	"""主窗口标题栏左上角图标"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    ico_path = os.path.join(current_dir, "icon.ico")
    try:
        if os.path.exists(ico_path):
            root.iconbitmap(ico_path) # tkinter原生设置窗口标题栏图标
    except Exception as e:
        pass

程序主程序入口使用,例:

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Aria2c控制器")
    root.geometry("780x470")
    root.resizable(False, False)
    set_window_icon()

托盘图标#

def get_tray_icon():
    """托盘图标"""
    # 获取程序当前所在的绝对目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接同目录下的 icon.ico 路径
    ico_path = os.path.join(current_dir, "icon.ico")
    try:
        # 优先尝试加载本地ICO文件
        if os.path.exists(ico_path):
            ico_img = Image.open(ico_path)
            return ico_img
    except Exception as e:
        pass
    
    # 备用方案
    icon_size = (64, 64)
    image = Image.new("RGB", icon_size, color="white")
    draw = ImageDraw.Draw(image)
    draw.rectangle([16, 16, 48, 48], fill="#00FF00")
    return image

例子:

def start_system_tray():
    global tray_icon
    tray_icon = pystray.Icon("Aria2c控制器", get_tray_icon(), "Aria2c控制器", create_tray_menu())
    tray_icon.left_click = lambda icon, item: show_main_window() if root.state() == "withdrawn" else hide_main_window()
    tray_icon.run()

让主窗口在屏幕正中央显示#

def center_window():
    """让主窗口在屏幕正中央显示,适配所有分辨率"""
    root.update_idletasks()
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    window_width = root.winfo_width()
    window_height = root.winfo_height()
    x = (screen_width - window_width) // 2
    y = (screen_height - window_height) // 2
    root.geometry(f"+{x}+{y}")

程序主程序入口使用,例:

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Aria2c控制器")
    root.geometry("780x470")
    root.resizable(False, False)
    center_window()

打包后的路径检测#

import sys
def get_app_dir():
    """获取程序实际运行目录"""
    if getattr(sys, 'frozen', False):
        # 打包后环境:sys.executable指向exe文件路径
        return os.path.dirname(os.path.abspath(sys.executable))
    else:
        # 开发环境:使用脚本所在目录
        return os.path.dirname(os.path.abspath(__file__))