在框架中居中对齐一组小部件 [英] Center align a group of widgets in a frame

查看:27
本文介绍了在框架中居中对齐一组小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果框架的行中有一个小部件,我可以使用 sticky= 将其对齐到任何一侧,或者通过省略 sticky 来居中对齐.

If there's a single widget in a frame's row, I can align it to any side with sticky=, or center align by omitting sticky.

但是,当一行中有多个列时,其中的对象会以左对齐结束:

However, when there are multiple columns in a row, objects in them end up left-aligned:

虽然我希望它们留在中心(同时保持尺寸).

while I wish for them to stay in the center (while maintaining size).

代码摘录:

from Tkinter import N,W,S,E,Tk
import ttk
import Tkinter as tkinter

root = Tk()
mainframe = ttk.Frame(root)
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

tv_town_fr = ttk.Frame(mainframe)
tv_town_fr.grid(row=3, sticky=(W,E))

tv_town_add = ttk.Button(tv_town_fr,text="+",width=4)
tv_town_add.grid(row=1,column=1)
tv_town_edit = ttk.Button(tv_town_fr,text="*",width=4)
tv_town_edit.grid(row=1,column=2)
tv_town_del = ttk.Button(tv_town_fr,text="-",width=4)
tv_town_del.grid(row=1,column=3)
tv_town_up = ttk.Button(tv_town_fr,text=u"↑",width=4)
tv_town_up.grid(row=1,column=4)
tv_town_down = ttk.Button(tv_town_fr,text=u"↓",width=4)
tv_town_down.grid(row=1,column=5)

tv_query_fr = ttk.Frame(mainframe)
tv_query_fr.grid(row=6, sticky=(W,E))

tv_query_add = ttk.Button(tv_query_fr,text="+",width=5)
tv_query_add.grid(row=1,column=1)
tv_query_edit = ttk.Button(tv_query_fr,text="*",width=5)
tv_query_edit.grid(row=1,column=2)
tv_query_del = ttk.Button(tv_query_fr,text="-",width=5)
tv_query_del.grid(row=1,column=3)
tv_query_up = ttk.Button(tv_query_fr,text=u"↑",width=5)
tv_query_up.grid(row=1,column=4)
tv_query_down = ttk.Button(tv_query_fr,text=u"↓",width=5)
tv_query_down.grid(row=1,column=5)

推荐答案

在使用 grid 时将一组小部件水平居中的最简单解决方案是在其左右两侧创建一个空列所有可见项目,然后为这些列赋予权重,以便将所有额外空间分配给空列.

The simplest solution for horizontally centering a group of widgets when using grid is to create an empty column to to the left and right of all of the visible items, and then give those columns a weight so that all extra space is allocated to the empty columns.

import Tkinter as tk

root = tk.Tk()
root.geometry("400x200")

label = tk.Label(root, text="Hello, world")
buttons = tk.Frame(root)
label.pack(side="top", fill="both", expand=True)
buttons.pack(side="bottom", fill="x")

b1 = tk.Button(buttons, text="one")
b2 = tk.Button(buttons, text="two")
b3 = tk.Button(buttons, text="three")

b1.grid(row=0, column=1)
b2.grid(row=0, column=2)
b3.grid(row=0, column=3)

# give empty columns a weight so that the consume
# all extra space
buttons.grid_columnconfigure(0, weight=1)
buttons.grid_columnconfigure(4, weight=1)

root.mainloop()

这篇关于在框架中居中对齐一组小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆