gpt4 book ai didi

python - tkinter:创建空根窗口时如何不显示它

转载 作者:太空宇宙 更新时间:2023-11-03 17:06:25 24 4
gpt4 key购买 nike

我有一个创建窗口的简单脚本:

import Tkinter as tk

def center(win):
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))

def showDialog():
print "tkinter"
root = tk.Tk()
root.title("Say Hello")
label = tk.Label(root, text="Hello World")
label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
button = tk.Button(root, text="OK", command=lambda: root.destroy())
button.pack(side="bottom", fill="none", expand=True, padx=10, pady=10)
center(root)
root.attributes("-topmost", True)
root.mainloop()

showDialog()

运行此脚本时,第一个空窗口会显​​示在屏幕的左上角,然后完整的窗口会显示在屏幕中央。

我不想看到第一个空窗口(它只出现几毫秒,但这不太好)

我怎样才能做到这一点?

最佳答案

使用以下两种方法来隐藏或显示根窗口。

def hide(root):
root.withdraw()

def show(root):
root.update()
root.deiconify()

当您将根窗口的大小设置为 (1, 1) 居中时,您应该将窗口大小指定给 center 方法
这里不需要lambda,使用command=root.destroy

import Tkinter as tk

def center(win, width, height):
win.update_idletasks()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))

def show(root):
root.update()
root.deiconify()

def hide(root):
root.withdraw()

def showDialog():
print "tkinter"
root = tk.Tk()
hide(root)
root.title("Say Hello")
label = tk.Label(root, text="Hello World")
label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
button = tk.Button(root, text="OK", command=root.destroy)
button.pack(side="bottom", fill="none", expand=True, padx=10, pady=10)
center(root, width=200, height=200)
show(root)
root.mainloop()

showDialog()

关于python - tkinter:创建空根窗口时如何不显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34554347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com