簡體   English   中英

Tkinter 中心 Label 在 GUI

[英]Tkinter center Label in the GUI

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

以上是我的 Tkinter GUI 代碼,但我希望在根/窗口的中心有 label 我該怎么做? 目前它位於按鈕之上,其他一切都很好,按鈕事件和這樣的作品

在我看來,你應該使用 place 或 grid 而不是 pack。 因為 pack 只提供很少的 alignment 選項。

否則,可能將主 window 分成兩個框架,然后將 label 包裝在下框架的頂部

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)

我希望這會有所幫助。 但是您應該使用網格以獲得更好的 alignment 或放置。

您可以使用以下命令將 label 放置在中心

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

同樣,您也可以將button.place(x=100, y=25)用於按鈕

REF: Tkinter: 中心 label 在固定尺寸的框架中?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM