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

Tkinter全屏窗口固定退出与最小化按钮位置问题咨询

Tkinter全屏窗口自定义按钮位置无法固定问题解决

问题描述

是否有函数可实现仅带有退出按钮(X)和最小化按钮(-)的全屏项目?

我的代码如下:

from tkinter import *
import tkinter as tk


def minimize_window():
    root2.iconify()

def exit_fullscreen():
    root2.destroy()    

def new_root():
    global root2, time_label
    root2 = Tk()
    root2.title("MONEY")
    root2.geometry('1500x700')
    
    # 开启全屏模式
    root2.attributes('-fullscreen', True)
    root2.resizable(False, False)
    
    # 创建退出按钮(X)
    exit_button = Button(root2, text="X", font="ar 15 bold", command=exit_fullscreen, bg='red', fg='white')
    exit_button.place(x=1450, y=10)  # 定位到右上角
    
    # 创建最小化按钮(-)
    minimize_button = Button(root2, text="-", font="ar 15 bold", command=minimize_window, bg='gray', fg='white')
    minimize_button.place(x=1400, y=10)  # 定位在退出按钮左侧
    

root2.mainloop()

运行上述代码后,已实现全屏模式及两个按钮,但按钮位置无法固定在指定位置,请问问题出在哪里?

问题原因

  • 固定坐标不兼容多分辨率:你直接使用x=1450、x=1400这类固定像素值,但全屏窗口宽度等于当前屏幕的实际分辨率宽度,不同屏幕尺寸下这个值差异极大,导致按钮要么超出可视区域,要么偏离预期位置。
  • 代码执行逻辑错误:new_root()函数未被调用,直接执行root2.mainloop()会触发变量未定义的错误,这是代码的潜在bug。
  • 无效的尺寸设置:root2.geometry('1500x700')会被全屏属性-fullscreen覆盖,完全不起作用。

解决方案

要让按钮固定在右上角,需根据屏幕实际宽度动态计算坐标,同时修正代码执行逻辑:

from tkinter import *
import tkinter as tk

def minimize_window():
    root2.iconify()

def exit_fullscreen():
    root2.destroy()    

def new_root():
    global root2
    root2 = Tk()
    root2.title("MONEY")
    
    # 启用全屏模式
    root2.attributes('-fullscreen', True)
    root2.resizable(False, False)
    
    # 获取当前屏幕宽度
    screen_width = root2.winfo_screenwidth()
    # 定义按钮宽度、边距和间距(可按需调整)
    btn_width = 2
    right_margin = 10
    btn_gap = 10
    
    # 创建退出按钮,动态计算右上角位置
    exit_btn = Button(root2, text="X", font="ar 15 bold", command=exit_fullscreen, bg='red', fg='white', width=btn_width)
    exit_btn.place(x=screen_width - right_margin - btn_width*10, y=10)
    
    # 创建最小化按钮,定位在退出按钮左侧
    minimize_btn = Button(root2, text="-", font="ar 15 bold", command=minimize_window, bg='gray', fg='white', width=btn_width)
    minimize_btn.place(x=screen_width - right_margin - btn_width*20 - btn_gap, y=10)
    
    # 确保按钮始终在界面最上层,避免被其他控件遮挡
    exit_btn.lift()
    minimize_btn.lift()

# 调用函数初始化窗口
new_root()
root2.mainloop()

关键优化点

  • 用root2.winfo_screenwidth()获取屏幕宽度,动态计算按钮x坐标,适配所有分辨率。
  • 调用lift()方法确保自定义按钮始终在界面最上层。
  • 修复了未调用new_root()的逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:17:35