Python tkinter:如何在创建空根窗口时不显示它
我有一个创建窗口的简单脚本:Python tkinter:如何在创建空根窗口时不显示它,python,tkinter,Python,Tkinter,我有一个创建窗口的简单脚本: 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
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)
,应将窗口大小指定给居中方法
此处不需要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()
我正在尝试你的脚本,但它似乎根本没有使窗口居中,更不用说经过一段短暂的时间。我目前没有使用Tkinter的机器,因此我无法使用你的代码,但你可以使用该方法隐藏根或顶级窗口,和用于重新显示。我已经尝试过撤消/取消显示,但它只显示一种阴影而不是窗口。我不知道这个影子是什么。注意:我正在MAC 10.6上运行python。没有win.update_idletasks()
,它如何工作?@furas:删除win.update_idletasks()
没有帮助(行为没有改变)@Laurent D。检查此项感谢您的代码和解释。我现在明白错在哪里了:我试图使用以前从未建造过的窗户的尺寸。但在您的示例中,窗口的大小是固定的。我想大小适合的内容(在我的完整代码,文本的长度将有所不同)。我该怎么做?@LaurentD.replacecenter()
为root.eval('tk::PlaceWindow%s center'%root.winfo_路径名(root.winfo_id()))
,在这种情况下,不需要hide()
和show()
方法。谢谢,它可以工作。我对特金特很陌生。你能解释一下这行新代码吗?@LaurentD。我们使用eval
来利用Tcl/Tk扩展,并且Tk
提供了一个可以使窗口居中的函数(Tk::PlaceWindow
)。