tkinter:如何在创建时不显示空的根窗口 [英] tkinter: how to not display the empty root window when creating it

查看:53
本文介绍了tkinter:如何在创建时不显示空的根窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple script that creates a window:

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()

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

When running this script, a first empty window is displayed on the top left part of the screen and then the complete window is displayed centered in the screen.

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

I would like to not see this first empty window (it appears only for few milliseconds, but this is not nice)

我该怎么做?

推荐答案

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

Use the following two methods to hide or show the root window.

def hide(root):
    root.withdraw()

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

当您将根窗口居中时,其大小为 (1, 1),您应该将窗口大小赋予 center 方法.
这里不需要lambda,使用command=root.destroy.

When you center the root window its size is (1, 1), you should give window size to center method.
lambda is not needed here, use 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:如何在创建时不显示空的根窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆