用witdraw()隐藏弹出框会导致窗口尺寸不合适

时间:2018-12-21 11:52:44

标签: python-2.7 tkinter

我正在tkinter中创建一个弹出窗口,并希望将其隐藏直到创建,标记并居中显示在屏幕上,以防止该窗口在错误的位置短暂闪烁为空。

但是如果我实现这些,则如果窗口的内容从未被pack()分发并且窗口的大小设置为默认的200 x 200 px,则生成的窗口将起作用。

我也尝试了after()update_idletasks(),因为我按绘画顺序猜出了问题,但没有成功。

要隐藏它,我使用withdraw()deiconify()函数,如包括此在内的许多其他文章所述: Tkinter - Preload window?

我得到的代码如下:

创建框架

class NotificationPopup(Tk.Toplevel):
    def __init__(self, root, text, title):
        Tk.Toplevel.__init__(self, root)

        # Hide window until created
        self.withdraw()

        # Slaved to parent. Shown over parent window
        self.transient(root)

        # Stops interaction with parent until child is solved
        self.grab_set()

        self.label = Tk.Label(self, text=text, justify=Tk.LEFT, padx=10)
        self.label.pack()
        self.button = Tk.Button(self, text='Ok', command=self.destroy)
        self.button.pack()
        self.button.focus_set()

        self.resizable(False, False)
        self.relief = Tk.GROOVE

        # Bind return to the button to close the window
        self.button.bind('<Return>', (lambda event: self.destroy()))

        Toolbox.center_toplevel(self)

        # Show window
        self.deiconify()

居中方法

# Center a window based on screen dimensions and window size
def center_toplevel(toplevel):
    toplevel.update_idletasks()

    # Toplevel window dimensions
    w = toplevel.winfo_width()
    h = toplevel.winfo_height()

    # get screen width and height
    ws = toplevel.winfo_screenwidth()  # width of screen
    hs = toplevel.winfo_screenheight()  # height of screen

    # calculate x and y coordinates for the Tk root window
    x = (ws / 2) - (w / 2)
    y = (hs / 2) - (h / 2)

    # Set dimension of window and placement on screen
    toplevel.geometry('%dx%d+%d+%d' % (w, h, x, y)) 

在我的应用程序上运行不带withdraw()的代码,显示宽度和高度分别为450和400 px,而包含withdraw()的宽度和高度则缩小为200 x 200 px,并且不适应其内容。< / p>

0 个答案:

没有答案