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

如何让tkinter中root.withdraw()与root.geometry()同时生效?

解决tkinter隐藏主窗口同时保留位置设置的问题

你遇到的问题是因为root.withdraw()会将主窗口从屏幕上移除,此时主窗口的位置设置无法传递给对话框。可以通过以下两种方法解决:

方法一:使用窗口透明属性替代隐藏

将主窗口设置为完全透明,视觉上和隐藏效果一致,但主窗口的位置、大小设置依然生效,对话框会基于这个透明窗口定位:

import tkinter as tk
from tkinter import simpledialog

root = tk.Tk()
root.geometry("340x100+50+500")
root.attributes('-alpha', 0)  # 设置主窗口完全透明

user_input = simpledialog.askfloat(title="输入框", prompt="请输入内容:", parent=root, initialvalue=34)
if user_input is not None:  # 处理用户取消输入的情况
    user_input = user_input * 60
root.destroy()

方法二:先设置位置再隐藏,手动调整对话框位置

如果必须使用withdraw(),可以先获取主窗口的位置参数,然后手动设置对话框的位置:

import tkinter as tk
from tkinter import simpledialog

root = tk.Tk()
root.geometry("340x100+50+500")
root.withdraw()

# 创建对话框实例,手动设置位置
dialog = simpledialog._QueryFloat(root, title="输入框", prompt="请输入内容:", initialvalue=34)
# 获取主窗口的位置,设置对话框到对应位置
root_x = root.winfo_x()
root_y = root.winfo_y()
dialog.geometry(f"+{root_x}+{root_y}")
user_input = dialog.result

if user_input is not None:
    user_input = user_input * 60
root.destroy()

补充说明

  • 注意处理用户点击取消的情况:askfloat在用户取消时会返回None,直接进行乘法运算会触发报错,所以需要加非空判断。
  • 方法一的兼容性更好,在不同系统上都能稳定生效;方法二直接操作对话框实例,需要注意tkinter版本的兼容性。

内容的提问来源于stack exchange,提问作者菜合馍馍

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 13:22:41