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

如何让Tkinter将窗口固定显示在屏幕指定位置?

解决Tkinter窗口固定位置问题(多屏环境)

原代码分两次调用geometry(),先设置尺寸再单独指定位置,在Windows多屏环境下可能因窗口初始化时序问题导致位置设置失效,出现窗口随机摆放的情况。以下是修正方案:

核心修改思路

  • 合并窗口尺寸与位置的设置,一次性调用geometry(),格式为{width}x{height}+{x}+{y},避免时序问题
  • 根据你的多屏布局确认目标坐标范围:
    • 主屏(3840x2160):x坐标范围0 ~ 3840-窗口宽度,y坐标范围0 ~ 2160-窗口高度
    • 副屏(1920x1080):若副屏在主屏右侧,x坐标范围3840 ~ 5760-窗口宽度,y坐标范围0 ~ 1080-窗口高度;若副屏在主屏下方,x坐标范围0 ~ 1920-窗口宽度,y坐标范围2160 ~ 3240-窗口高度(根据实际布局调整)

修改后的代码

class TkConfigParameters(tk.Tk):
    
    def __init__(self, shared_world_inst):
        super().__init__()
        self.shared_world_inst = shared_world_inst

        self.shared_utils_inst = SharedUtils(self.shared_world_inst)  # Create an instance of SharedUtils
        print('in TkConfig_Parameters\n')
        print(f'Type of shared_world_inst: {type(self.shared_world_inst)}')
        self.shared_utils_inst.print_niao()  # Call the print_niao method

        # get screen width and height
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()

        self.title("Configuration Parameters")
        
        # 一次性设置窗口尺寸和固定位置
        width = 600
        height = 300
        # 示例:放在主屏左上角(x=100, y=100)
        x = 100  
        y = 100  
        # 若要放在副屏右侧,可改为:x = 3940(主屏宽度3840+100),y = 100
        # x = 3940
        # y = 100
        self.geometry(f"{width}x{height}+{x}+{y}")

修改后窗口会直接以指定的尺寸和位置初始化,在多屏环境下能稳定固定到目标位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 14:40:04