在Tkinter中,可以使用anchor
和justify
属性来控制按钮和标签的居中。下面是一个示例代码,展示了如何在Tkinter中居中按钮和标签:
import tkinter as tk
def center_widgets():
root.update_idletasks()
width = root.winfo_width()
height = root.winfo_height()
button_x = (width - button.winfo_width()) // 2
button_y = (height - button.winfo_height()) // 2
button.place(x=button_x, y=button_y)
label_x = (width - label.winfo_width()) // 2
label_y = (height - label.winfo_height()) // 2 - 50
label.place(x=label_x, y=label_y)
root = tk.Tk()
root.geometry("400x300")
button = tk.Button(root, text="按钮")
button.pack()
label = tk.Label(root, text="标签")
label.pack()
root.bind("", lambda e: center_widgets())
root.mainloop()
在上面的示例中,我们定义了一个center_widgets
函数,该函数在窗口大小改变时被调用。在函数中,我们获取窗口的宽度和高度,并根据它们计算按钮和标签的x和y坐标,使它们居中显示。最后,我们使用place
方法将按钮和标签放置在计算得到的坐标位置。
通过绑定
事件到root
窗口,我们可以在窗口大小改变时自动调用center_widgets
函数。这样,无论窗口大小如何改变,按钮和标签都会始终保持居中。
上一篇:按钮和标签在过渡后消失。