使用 TK python 将按钮与 window 的中心对齐

Align buttons to the center of a window with TK python

我有一个使用 TK 构建用户界面的小 python 脚本。 我无法将两个按钮 "Start""Cancel" 对齐到 window 的中心。现在它们在左下角,但我想将它们放在中间(底部)。这是我的代码:

import sys, os
import tkinter as tk
from tkFileDialog   import askopenfilename
from Tkinter import *
from tkMessageBox import *


root = tk.Tk()
root.title("My Program")
root.geometry("450x250+500+200")

def star_program():
   print "start"

def sel():
   selection = "You selected the option " + str(var.get())
   label.config(text = selection)

def open_file_1():
    os.system("gedit /home/user/Desktop/1.txt")

def open_file_2():
    os.system("gedit /home/user/Desktop/2.txt")

tk.Label(root, 
     text="""Hello World""",
     justify = tk.LEFT,
     bd = 12, padx = 20, font = 'Arial 11 bold').pack()

var = IntVar()
R1 = Radiobutton(root, text="Choise (1)", variable=var, value=1)
R1.pack( anchor = W )

R2 = Radiobutton(root, text="Choise (2)", variable=var, value=2)
R2.pack( anchor = W )

R3 = Radiobutton(root, text="Choise (3)", variable=var, value=3)
R3.pack( anchor = W )


B = tk.Button(root, text ="Open File 1", font = 'Arial 10 bold', command = open_file_2)
B.pack( anchor = W )

C = tk.Button(root, text ="Open File 2", font = 'Arial 10 bold', command = open_file_1)
C.pack( anchor = W )

label = Label(root)
label.pack()

start_button = Button(root, 
               text="Start",
               command=star_program)
cancel_button = Button(root,
               text="Cancel",
               command=quit)

start_button.pack(side = LEFT)
cancel_button.pack(side = LEFT)

root.mainloop()

我尝试在 pack 中使用不同的选项,例如 x & y 或 side = bottom,但没有。 任何想法? 谢谢

一个简单的解决方案是将它们放在一个框架中,然后将 pack 该框架的 side 选项设置为 'bottom'。替换:

start_button = Button(root, 
               text="Start",
               command=star_program)
cancel_button = Button(root,
               text="Cancel",
               command=quit)

start_button.pack(side = LEFT)
cancel_button.pack(side = LEFT)

与:

start_cancel = tk.Frame(root)
start_cancel.pack(side='bottom')

start_button = tk.Button(start_cancel, 
               text="Start",
               command=star_program)
cancel_button = tk.Button(start_cancel,
               text="Cancel",
               command=quit)

start_button.pack(side = 'left')
cancel_button.pack(side = 'left')

请注意,您似乎随机使用了 from Tkinter import *import tkinter as tk 中的属性,这使得您的代码难以阅读。