使用TK python将按钮对齐到窗口的中心

时间:2018-01-09 08:02:21

标签: python tkinter tk

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

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()

我尝试在包内使用不同的选项,例如x& y或side = bottom,但没什么。 任何的想法? 感谢

1 个答案:

答案 0 :(得分:0)

一个简单的解决方案是将它们放在一个框架中,并将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的属性,这似乎是随机的,这使得您的代码与读取相当不一致。