tkinter窗口跟随TeraTerm
要实现这个需求,可以通过以下步骤使用 Python 实现(基于 Windows API 和 Tkinter):
import tkinter as tk
import win32gui
import win32con
import time
import threading
import re
class FloatingControl:
def __init__(self):
# 创建主窗口
self.root = tk.Tk()
self.root.overrideredirect(True) # 隐藏标题栏
self.root.attributes("-topmost", True) # 始终置顶
self.root.configure(bg='lightgray')
# 自定义控件内容(示例)
self.label = tk.Label(self.root, text="Control Panel", bg='lightgray')
self.label.pack(padx=10, pady=5)
self.button = tk.Button(self.root, text="Action", command=self.on_button_click)
self.button.pack(padx=10, pady=5)
# 监控线程控制
self.monitor_thread = None
self.running = False
# 绑定窗口关闭事件
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
def on_button_click(self):
"""示例按钮点击事件"""
print("Button clicked!")
def start_monitoring(self):
"""启动窗口监控线程"""
self.running = True
self.monitor_thread = threading.Thread(target=self.monitor_window)
self.monitor_thread.daemon = True
self.monitor_thread.start()
self.root.mainloop()
def on_close(self):
"""关闭窗口时清理资源"""
self.running = False
self.root.destroy()
def find_teraterm_window(self):
"""查找 Tera Term 窗口句柄"""
def callback(hwnd, _):
title = win32gui.GetWindowText(hwnd)
# 匹配 Tera Term 窗口标题(根据实际情况调整正则表达式)
if re.match(r'Tera Term VT - COM\d+', title):
self.tera_hwnd = hwnd
self.tera_hwnd = None
win32gui.EnumWindows(callback, None)
return self.tera_hwnd
def monitor_window(self):
"""持续监控目标窗口状态"""
while self.running:
hwnd = self.find_teraterm_window()
if hwnd:
# 获取窗口位置和状态
rect = win32gui.GetWindowRect(hwnd)
style = win32gui.GetWindowLong(hwnd, win32con.GWL_STYLE)
# 判断窗口是否可见
if (style & win32con.WS_VISIBLE) and not (style & win32con.WS_MINIMIZE):
# 计算控件位置
tera_left, tera_top, tera_right, tera_bottom = rect
control_width = 150 # 根据实际控件宽度调整
x = tera_right - control_width - 10 # 右侧偏移10像素
y = tera_top + 30 # 顶部偏移30像素
# 更新控件位置
self.root.geometry(f"+{x}+{y}")
self.root.deiconify()
else:
self.root.withdraw()
else:
self.root.withdraw()
time.sleep(0.1) # 监控间隔
if __name__ == "__main__":
app = FloatingControl()
app.start_monitoring()
使用说明:
- 依赖安装:
pip install pywin32 tkinter
- 功能特点:
- 自动吸附在 Tera Term 窗口右上角
- 跟随目标窗口移动和缩放
- 目标窗口最小化时自动隐藏
- 置顶显示
- 可自定义控件内容
- 需要调整的参数:
# 修改此处正则表达式以匹配你的 Tera Term 窗口标题
re.match(r'Tera Term VT - COM\d+', title)
# 调整控件位置偏移量
control_width = 150 # 控件宽度
x = tera_right - control_width - 10 # 右侧偏移
y = tera_top + 30 # 顶部偏移
- 扩展建议:
- 添加更多交互控件(输入框、状态显示等)
- 增加配置文件保存位置参数
- 支持多个 Tera Term 窗口的跟踪
- 添加窗口拖拽调整位置功能
注意:该实现基于以下假设:
- Tera Term 窗口标题包含 "Tera Term VT - COM" 格式
- 运行在 Windows 系统上
- Tera Term 使用标准窗口样式
如果需要更精确的控制,可以进一步:
- 使用
GetWindowPlacement
替代GetWindowRect
- 添加窗口消息钩子实现实时监控
- 使用 DPI 感知坐标计算