<p>在根窗口中居中<strong>框架</strong>的方法如下:</p>
<blockquote>
<p>Part A) Create A window with a specific size <code>h</code>, <code>w</code> (since it is a
popup - in this example I disable resizing it ). Inside the frame- a
<code>Label</code> and a <code>Button</code>:</p>
</blockquote>
<pre><code>root = Tk()
w = '200'
h = '80'
root.geometry('{}x{}'.format(w, h))
root.configure(bg='lightgreen') ###To diff between root & Frame
root.resizable(False, False)
txt = StringVar()
txt.set("This is an error message")
testframe = ttk.Frame(root)
testframe.grid(row=0, column=1)
label1 = ttk.Label(testframe, textvariable=txt)
label1.grid(row=0, column=0, pady=10)
ok_button = ttk.Button(testframe, text="OK", command=root.destroy)
ok_button.grid()
</code></pre>
<blockquote>
<p>Part B) In order to get frame's dimensions ( including <code>Label</code> and
<code>Button</code> inside ) we use <code>testframe.update()</code> and then
<code>testframe.winfo_width()</code> <code>testframe.winfo_height()</code> to obtain frame's
updated values. <code>xbias</code> and <code>ybias</code> calculates the center to place the
frame in the middle:</p>
</blockquote>
<pre><code>testframe.update()
xbias = int(w) / 2 - testframe.winfo_width() / 2
ybias = int(h) / 2- testframe.winfo_height() / 2
testframe.grid(row=0, column=1, pady=ybias, padx=xbias)
root.mainloop()
</code></pre>