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

如何让PySimpleGUI新窗口在原窗口所在的非主屏幕显示?

PySimpleGUI多窗口跨显示器定位解决方案

问题核心

move_to_center()方法默认仅将窗口居中到主显示器,无法识别副显示器的位置范围,导致你判断坐标为负后调用该方法,窗口仍回到主屏幕。要实现新窗口跟随前一个窗口所在显示器,需先定位目标显示器再计算居中位置。

修正后的实现代码

import screeninfo
import PySimpleGUI as sg

def correct_location(window, current_location):
    x_window, y_window = current_location
    target_monitor = None

    # 遍历所有显示器,匹配窗口所在的目标显示器
    for monitor in screeninfo.get_monitors():
        monitor_right = monitor.x + monitor.width
        monitor_bottom = monitor.y + monitor.height
        # 判断窗口左上角坐标是否处于当前显示器范围内
        if monitor.x <= x_window < monitor_right and monitor.y <= y_window < monitor_bottom:
            target_monitor = monitor
            break

    if target_monitor:
        # 计算目标显示器的中心位置,同时偏移窗口自身的半宽半高以实现真正居中
        win_width, win_height = window.size
        center_x = target_monitor.x + (target_monitor.width - win_width) // 2
        center_y = target_monitor.y + (target_monitor.height - win_height) // 2
        window.move(center_x, center_y)
    else:
        # 异常情况 fallback 到主屏幕居中
        window.move_to_center()

代码说明

  1. 显示器匹配逻辑:通过对比窗口左上角坐标与每个显示器的坐标范围(从monitor.x到monitor.x+width,monitor.y到monitor.y+height),找到窗口所在的目标显示器。
  2. 居中计算:直接计算目标显示器的中心区域时,需要用显示器尺寸减去窗口尺寸的一半,确保窗口整体居中,而非窗口左上角在显示器中心。
  3. 异常处理:如果窗口位置超出所有显示器范围,仍保留主屏幕居中的兜底逻辑。

适配你的场景

结合你提供的运行输出,前一个窗口位置(-1441, 340)落在DISPLAY2(x范围-19200,y范围01080)内,代码会自动计算该显示器的中心坐标,将新窗口移动到对应位置,而非回到主屏幕。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:35:27