tkinter: how to not display the empty root window when creating it

后端 未结 1 509
既然无缘
既然无缘 2021-01-15 21:41

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.w         


        
相关标签:
1条回答
  • 2021-01-15 22:19

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

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

    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()
    
    0 讨论(0)
提交回复
热议问题