简体   繁体   English

如何将 Tkinter 中的小部件居中对齐

[英]How to align widgets in Tkinter to center

I am working on a simple counter app in tkinter.我正在 tkinter 中开发一个简单的计数器应用程序。 I rigged up some code looking at few tutorial on web.我在网上查看了一些教程,编写了一些代码。 All the functions of a counter are set up.一个计数器的所有功能都设置好了。 But when it comes to the designing of the app, I want the Count, the Count button, and the reset button to be aligned at the center.但是在设计应用程序时,我希望计数、计数按钮和重置按钮居中对齐。

The code is as below代码如下

from tkinter import Label, Button, Tk
from tkinter import font


window = Tk()

window.geometry('500x500')

window.title("Counter")

window.count = 0

def increment():
    window.count += 1
    lbl.configure(text=window.count)


def reset():
    window.count = 0
    lbl.configure(text=window.count)


lbl = Label(window, text="0", font=("Apple Braille", 60))
lbl.grid(column=0, row=0)

btn1 = Button(window, text="Count", command=increment)
btn1.grid(column=0, row=1)

btn2 = Button(window, text="Reset", command=reset)
btn2.grid(column=1, row=1)

btn1['font'] = btn2['font'] = font.Font(size=30)

window.mainloop()

A Screenshot of my counter app is here我的计数器应用的屏幕截图在这里

Tkinter Count app 截图

Any help in this aspect will be appreciated.在这方面的任何帮助将不胜感激。

Thanks,谢谢,

It is easier to use pack() instead of grid() for your requirement.根据您的要求使用pack()而不是grid()更容易。

lbl = Label(window, text="0", font=("Apple Braille", 60))
lbl.pack()

# frame for the two buttons
frame = Frame(window)
frame.pack()

btn1 = Button(frame, text="Count", command=increment)
btn1.grid(column=0, row=1)

btn2 = Button(frame, text="Reset", command=reset)
btn2.grid(column=1, row=1)

If you want to put at the center of the window:如果你想放在窗口的中央:

# frame for the label and buttons
frame = Frame(window)
frame.place(relx=0.5, rely=0.5, anchor="c") # put at center of window

lbl = Label(frame, text="0", font=("Apple Braille", 60))
lbl.grid(row=0, column=0, columnspan=2)

btn1 = Button(frame, text="Count", command=increment)
btn1.grid(column=0, row=1)

btn2 = Button(frame, text="Reset", command=reset)
btn2.grid(column=1, row=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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