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

时间:2016-01-01 07:21:34

标签: 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_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()

运行此脚本时,屏幕左上角会显示第一个空白窗口,然后整个窗口将以屏幕为中心显示。

我不希望看到第一个空窗口(它只显示几毫秒,但这不太好)

我该怎么做?

1 个答案:

答案 0 :(得分:0)

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

def hide(root):
    root.withdraw()

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

当您将根窗口的中心大小设为(1, 1)时,您应该将窗口大小设为center method
此处不需要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()