python - 如何控制 Tkinter 网格中的标签位置和间距
问题描述
现在我想在同一行制作食品价格,因此我也将其更改为第 2 行,但输出是这样的
食物回到第 0 行,为什么会这样?我试图得到这样的东西:
foodprice=['3','2','1.50']
drinks = ['Water','Hot water','Medium water']
drinksprice = ['1','2','3']
myFrame3 = Frame(root, bg = '')
myFrame3.pack()
myFrame3.columnconfigure(0, weight=1)
myFrame3.columnconfigure(1, weight=2)
for x in range (len(food)):
foodop = Label(myFrame3, font=("Impact", "15"), text = food[x])
foodop.grid(row = 2+x, column = 4) # <--
for x in range (len(foodprice)):
fprice = Label(myFrame3, font=("Impact", "15"), text = foodprice[x])
fprice.grid(row = 2+x, column = 8) # <--
for x in range (len(drinks)):
drinksop = Label(myFrame3, font=("Impact", "15"), text = drinks[x])
drinksop.grid(row = 4+(len(food))+x, column = 4) # <--
for x in range (len(drinksprice)):
drinksp = Label(myFrame3, font=("Impact", "15"), text = drinksprice[x])
drinksp.grid(row = 4+(len(food))+x, column = 8) # <--
解决方案
在文本周围创建空白区域不像在电子表格程序中那样工作。
如果没有设置权重rowconfigure()
来防止这种情况,Tkinter 会折叠完全空的网格行。列也是如此。
像这样的布局:
import tkinter as tk
root = tk.Tk()
def place(col, row, text='Label', color='white'):
label = tk.Label(root, text=text, bg=color)
label.grid(column=col, row=row,
ipadx=10, ipady=10, padx=1, pady=1, sticky="NSEW")
def make_layout(cols, rows):
for c in cols:
place(c, 0, c, 'lightgrey')
for r in rows:
place(0, r, r, 'lightgrey')
for r in rows:
for c in cols:
place(c, r, 'Label')
make_layout((1,2),(1,2))
root.mainloop()
...看起来完全像这样:
无需将列中的权重配置8
为29
,行中的权重5
为49
。
(要得到这个,在代码中替换make_layout((1,2),(1,2))
为make_layout((7,30),(4,50))
!)
即使您添加了权重,标签仍然高于加权的空行,因此布局可能看起来不像您想象的那么干净。
Tkinter 的 Grid Geometry Manager是我前几天阅读的一个很好的教程,其中详细介绍了这一点。还介绍了函数的可选columnspan
和rowspan
参数grid()
。
最后但并非最不重要的一点是,您应该看看如何在 Tkinter 中的标签中证明文本的合理性
推荐阅读
- asp.net-core - 使用 aspnetboilerplate 配置 swagger 时出现问题
- excel - Excel/VBA/SQL 从一行中获取值并在另一行中更新
- java - Hbase FilterList as MUST_PASS_ONE 与两个 RowFilters 返回所有内容
- three.js - 使用 Mali GPU 的 Three.js 中对象的奇怪抖动
- regex - URL 匹配正则表达式:正面和负面术语
- java - Java SocketChannel 无法向 ServerSocketChannel 发送数据
- java - 动画运行不流畅(旋转)
- c# - 将数据表与公式绑定时的 C# ReoGrid 性能问题
- javascript - 数组丢失内容javascript
- mysql - 为什么“输入字符串的格式不正确。” 在 mySQL 的查询中?