如何在PySimpleGUI中检测窗口移动事件?
实现PySimpleGUI窗口移动检测的方法
PySimpleGUI本身没有提供原生的WIN_MOVED事件,但可以通过绑定底层Tkinter框架的<Configure>事件来实现窗口移动监测,步骤如下:
- 获取PySimpleGUI窗口对应的底层Tkinter窗口对象(通过
window.TK属性) - 绑定
<Configure>事件,该事件会在窗口位置或大小变化时触发 - 通过对比窗口前后位置,过滤出仅位置变化的情况(排除窗口 resize 事件)
示例代码:
import PySimpleGUI as sg # 创建简单布局和窗口 layout = [[sg.Text("拖动窗口即可触发移动检测")]] window = sg.Window("窗口移动检测演示", layout) # 记录初始窗口位置 prev_x, prev_y = window.current_location() # 定义Configure事件的处理函数 def handle_configure(event): global prev_x, prev_y # 获取当前窗口位置 curr_x, curr_y = window.current_location() # 判断是否是位置变化(而非大小变化) if curr_x != prev_x or curr_y != prev_y: print(f"窗口已移动,新位置:({curr_x}, {curr_y})") # 更新记录的位置 prev_x, prev_y = curr_x, curr_y # 绑定Tkinter的Configure事件 window.TK.bind("<Configure>", handle_configure) # 主事件循环 while True: event, values = window.read() if event == sg.WIN_CLOSED: break window.close()
说明:
<Configure>事件会在窗口尺寸调整或位置移动时触发,因此需要通过前后坐标对比确认是移动事件window.current_location()方法用于获取窗口左上角的当前坐标,是PySimpleGUI提供的便捷方法
内容的提问来源于stack exchange,提问作者Ralph Freshour
相关产品推荐
相关产品推荐

