Home > front end >  Tkinter center Label in the GUI
Tkinter center Label in the GUI

Time:12-27

import tkinter as tk
from tkinter import *

HEIGHT = 600
WIDTH = 600

root = tk.Tk()

def button_event1():
    import ThreePlayers
    print(ThreePlayers)

def button_event2():
    import TwoPlayersGame
    print(TwoPlayersGame)


def button_event3():
    print("")

def button_event4():
    print("")

def button_event5():
    quit()

root = Tk()
root.title('Connect 4 Game')

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
L.config(anchor=CENTER)
L.pack()

button = tk.Button(root, text="3 Player Game", command=button_event1)
button.pack()

button = tk.Button(root, text="2 Player Game", command=button_event2)
button.pack()

button = tk.Button(root, text="1 Player Game", command=button_event3)
button.pack()

button = tk.Button(root, text="Options", command=button_event4)
button.pack()

button = tk.Button(root, text="QUIT", command=button_event5)
button.pack()

root.mainloop()

Above is my Code for a Tkinter GUI but I want the have the label at the center of the root/window how do I do that? Currently its sitting on top of the buttons everything else is fine the button events and such works

CodePudding user response:

In my opinion, you should have used place or grid instead of pack. Because pack only gives few alignment options.

otherwise, maybe divide the main window into two frames then pack the label at the top of the lower frame

frame = Frame(root)
frame.pack()

bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )


L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
L.pack(side = TOP)

I wish this helps. but you should use grid for better alignment or place.

CodePudding user response:

You can use the following commands to place the label in the center

L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
# L.config(anchor=CENTER)
# L.pack()
L.place(x=HEIGHT/2, y=WIDTH/2, anchor="center")

Similarly, you can also use button.place(x=100, y=25) for buttons

REF: Tkinter: Center label in frame of fixed size?

  • Related