简体   繁体   中英

Tkinter: How to make a button center itself?

I'm making a program in Python and I want to go with a layout that is a bunch of buttons in the center. How do I make a button center itself using pack()?

If this can't resolve your problem

button.pack(side=TOP)

You'll need to use the method

button.grid(row=1,col=0)

the values of row=1,col=0 depend of the position of the other widget in your window

or you can use .place(relx=0.5, rely=0.5, anchor=CENTER)

button.place(relx=0.5, rely=0.5, anchor=CENTER)

Example using .place() :

from tkinter import *  # Use this if use python 3.xx
#from Tkinter import *   # Use this if use python 2.xx
a = Button(text="Center Button")
b = Button(text="Top Left Button")
c = Button(text="Bottom Right Button")

a.place(relx=0.5, rely=0.5, anchor=CENTER)
b.place(relx=0.0, rely=0.0, anchor=NW)
c.place(relx=1.0, rely=1.0, anchor=SE)
mainloop()

传统知识窗口

this is slightly old now, you have to do this:

import tkinter as tk #you can do 'from tkinter import *', any is fine
btn = tk.Button(text = "Centered Button")
btn.place(relx=0.5, rely=0.5, anchor='center')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM