如何完全移除tkinter标签的垂直填充?

3
最初的回答:我想使用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)

这是一个展示样式的图片: screnshot 我想要去掉文本下面(和上面)的绿色空白。最初的回答:

我认为这是因为标签为下行字母保留了空间,例如'g'。由于使用了大号字体,所以额外的空间也很大,但如果在文本后面加上'g',你会发现它下面的空间并不多。 - j_4321
1个回答

1
无法通过Label来删除文本上方和下方的空格,因为高度对应于由字体大小决定的整数行数。 这种行高会为下降到基线以下的字母留出空间,例如 'g',但由于您不使用此类字母,因此在文本下方有大量空白空间(在我的计算机上顶部的额外空间并不多)。要删除此空格,可以使用Canvas而不是Label,并将其调整大小为较小的尺寸。
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()

result


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接