如何将按钮放在 ttk 中的框架上?

How can I center a button on a frame in ttk?

我无法使用 ttk 将按钮置于框架的中心:

上面例子的代码如下:

from tkinter import *
from tkinter.ttk import *

root = Tk()
root.title("button on a frame")

l = Label(root, text="why wont my button")
l2 = Label(root, text="on a frame center?")
l.grid(row=0, column=0)
l2.grid(row=1, column=1)

myStyle = Style()
myStyle.configure("green.TFrame", background="green")

bottomFrame = Frame(root, style="green.TFrame")
bottomFrame.grid(row=11, columnspan=2, sticky=E+W, pady=5)

runButton = Button(bottomFrame, text="Run")
runButton.grid(pady=5)

root.mainloop()

如果我在下面添加一个没有框架的按钮,它会居中。

您需要为 Frame 的行和列设置 weight

bottomFrame = Frame(root, style="green.TFrame")
bottomFrame.grid(row=11, columnspan=2, sticky=E+W+N+S, pady=5)
bottomFrame.grid_columnconfigure(0, weight=1)
bottomFrame.grid_rowconfigure(0, weight=1)

runButton = Button(bottomFrame, text="Run")
runButton.grid(pady=5)

weight (column):

A relative weight used to distribute additional space between columns. A column with the weight 2 will grow twice as fast as a column with weight 1. The default is 0, which means that the column will not grow at all.

weight (row):

A relative weight used to distribute additional space between rows. A row with the weight 2 will grow twice as fast as a row with weight 1. The default is 0, which means that the row will not grow at all.