简体   繁体   中英

How can I center a widget in python tkinter?

So basically I made this program that when you run it, it would open a form where you can fill out text entry and etc, but I want to centre the text entries in the form and I tried the anchor method but it just made it disappear.

import tkinter as tk

root = tk.Tk()
root.geometry("150x50+680+350")

def FormSubmission():
    global button_start
    root.attributes("-fullscreen", True)
    tk.Label(root, text="First Name:").grid(row=0)  
    e1 = tk.Entry(root) 
    e1.grid(row=0, column=1) 
    tk.Label(root, text="Last Name:").grid(row=1) 
    e2 = tk.Entry(root)
    e2.grid(row=1, column=1)
    button_start.place_forget()


button_start = tk.Button(root, text="Start", height=3, width=20, command = FormSubmission)
button_start.place(x = 0, y = 10)
button_exit = tk.Button(root, text="Exit", command=root.destroy)
button_exit.place(x=1506, y=0)

root.mainloop()

I want to anchor the text entry and the label next to them etc

You can add the widgets to be cantered in a separate frame,

frame=tk.Frame(root)
tk.Label(frame, text="First Name:").grid(row=0)  
e1 = tk.Entry(frame) 
e1.grid(row=0, column=1) 
tk.Label(frame, text="Last Name:").grid(row=1) 
e2 = tk.Entry(frame)
e2.grid(row=1, column=1)

and then use any of the below methods to center it

  • Using pack

     frame.pack(anchor='center',expand=True)
  • Using grid

     frame.grid() root.columnconfigure(0,weight=1) root.rowconfigure(0,weight=1)

The above methods would work to center the frame if that is the only widget in the parent that has been placed using pack / grid respectively, otherwise you will have to make changes accordingly.

  • Using place

     frame.place(relx=.5,rely=.5,anchor='center')

This would center the widget in the parent, overlapping the widgets (if any) that are present below.

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