You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在非全屏且保留任务栏图标时移除Tkinter应用标题栏?

解决方案:Tkinter移除标题栏但保留边框与任务栏图标

Windows平台实现方法

Tkinter原生API无法直接实现该需求,但可以通过Windows系统API修改窗口样式达成目标,步骤如下:

  1. 安装依赖库:
pip install pywin32
  1. 完整代码示例:
import tkinter as tk
import win32gui
import win32con

def remove_titlebar_keep_border(window):
    # 获取窗口句柄
    hwnd = win32gui.GetParent(window.winfo_id())
    # 获取当前窗口样式
    current_style = win32gui.GetWindowLongPtr(hwnd, win32con.GWL_STYLE)
    # 移除标题栏样式,同时保留可调整大小边框、系统菜单等必要样式
    new_style = current_style & ~win32con.WS_CAPTION | win32con.WS_THICKFRAME | win32con.WS_SYSMENU
    win32gui.SetWindowLongPtr(hwnd, win32con.GWL_STYLE, new_style)
    # 刷新窗口样式
    win32gui.SetWindowPos(hwnd, 0, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_FRAMECHANGED)

# 创建主窗口
root = tk.Tk()
root.title("无标题栏示例")
root.geometry("400x300")

# 移除标题栏并保留边框
remove_titlebar_keep_border(root)

# 实现窗口拖拽功能(原标题栏拖拽逻辑失效,需手动绑定)
def start_drag(event):
    root.drag_x = event.x
    root.drag_y = event.y

def drag_window(event):
    dx = event.x - root.drag_x
    dy = event.y - root.drag_y
    new_x = root.winfo_x() + dx
    new_y = root.winfo_y() + dy
    root.geometry(f"+{new_x}+{new_y}")

# 绑定拖拽事件到窗口(可按需绑定到特定区域)
root.bind("<ButtonPress-1>", start_drag)
root.bind("<B1-Motion>", drag_window)

root.mainloop()

说明:

  • 通过移除WS_CAPTION样式去掉标题栏,保留WS_THICKFRAME确保窗口可调整大小
  • 窗口会正常显示在任务栏,无需额外配置
  • 移除标题栏后默认拖拽功能失效,因此手动实现了拖拽逻辑

跨平台兼容方案

针对不同系统做分支处理,Linux可使用splash类型窗口,Windows沿用上述系统API方案:

import tkinter as tk
import sys

root = tk.Tk()
root.title("跨平台无标题栏")
root.geometry("400x300")

if sys.platform.startswith('linux'):
    # Linux桌面环境下,splash类型窗口会移除标题栏且保留边框(部分环境可能需调整)
    root.wm_attributes('-type', 'splash')
elif sys.platform == 'win32':
    # Windows平台使用系统API方案
    import win32gui
    import win32con
    hwnd = win32gui.GetParent(root.winfo_id())
    current_style = win32gui.GetWindowLongPtr(hwnd, win32con.GWL_STYLE)
    new_style = current_style & ~win32con.WS_CAPTION | win32con.WS_THICKFRAME | win32con.WS_SYSMENU
    win32gui.SetWindowLongPtr(hwnd, win32con.GWL_STYLE, new_style)
    win32gui.SetWindowPos(hwnd, 0, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_FRAMECHANGED)

    # 绑定拖拽事件
    def start_drag(event):
        root.drag_x = event.x
        root.drag_y = event.y

    def drag_window(event):
        dx = event.x - root.drag_x
        dy = event.y - root.drag_y
        root.geometry(f"+{root.winfo_x()+dx}+{root.winfo_y()+dy}")

    root.bind("<ButtonPress-1>", start_drag)
    root.bind("<B1-Motion>", drag_window)

root.mainloop()

关于你尝试的splash类型窗口:

这段代码在Linux下可以移除标题栏并保留边框,但Windows系统不支持该属性,因此无法达到预期效果。

内容的提问来源于stack exchange,提问作者user23470475

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 13:32:05