2

我想使用 tkinter 创建一个桌面应用程序。在标签中放置文本(大尺寸)时,我总是得到一个大的垂直填充。无论如何我可以摆脱这个额外的空间吗?我想将文本放在标签的底部。

我已经尝试设置 pady 以及文本锚。

self.lbl_temp = Label(self.layout, text='20°C', font=('Calibri', 140), bg='green', fg='white', anchor=S)
self.lbl_temp.grid(row=0, column=1, sticky=S)

这是它的外观图像:

截图

我想删除文本下方(和顶部)的绿色空间。

4

1 回答 1

1

无法使用 a 删除文本上方和下方的空格,Label因为高度对应于整数行,其高度由字体大小决定。此行高为低于基线的字母保留空间,例如“g”,但由于您不使用此类字母,因此文本下方有很多空白空间(我没有顶部的额外空间虽然在我的电脑上)。

要删除此空间,您可以使用 aCanvas而不是 aLabel并将其调整为更小。

import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, bg='green')
canvas.grid()
txtid = canvas.create_text(0, -15, text='20°C', fill='white', font=('Calibri', 140), anchor='nw')  
# I used a negative y coordinate to reduce the top space since the `Canvas` 
# is displaying only the positive y coordinates
bbox = canvas.bbox(txtid)  # get text bounding box
canvas.configure(width=bbox[2], height=bbox[3] - 40)  # reduce the height to cut the extra bottom space

root.mainloop()

结果

于 2019-08-13T16:31:52.037 回答