双下划线文本标记

2024-09-30 12:27:43 发布

您现在位置:Python中文网/ 问答频道 /正文

请我需要帮助使用双下划线的文本在tkinter。 示例代码是:

allbl=tk.Label(hmpage,text='Purchases', font='calibri 25 bold doubleunderline',fg='white',bg='#2a475e')
allbl.place(relx=0.45,rely=0.25,anchor="center")

Tags: 代码text文本示例tkinterlabeltkfont
3条回答

经过长时间的搜索,我不得不接受令人悲伤的现实,因为在撰写本文时,tkinter不支持双下划线功能

似乎您使用的字体属性不正确

我想说。。。 而不是写这封信:

font='calibri 25 bold doubleunderline'

写下:

font=('calibri', 25, 'bold underline')

而且我没有写doubleunderline,因为tkinter中没有类似的东西,所以您可以直接进行回溯

因此,正确的代码是:

allbl=tk.Label(hmpage,text='Purchases', font=('calibri', 25, 'bold underline'),fg='white',bg='#2a475e')
allbl.place(relx=0.45,rely=0.25,anchor="center")

没有用于双下划线的字体选项,因此无法使用简单的Label小部件完成此操作。但是,可以基于Canvas创建自定义类,在文本下方绘制两行:

import tkinter as tk
from tkinter.font import Font

class DblUnderlineLabel(tk.Canvas):
    def __init__(self, master, **kw):
        # collect text's properties
        font = Font(master, kw.pop('font', ''))
        text = kw.pop('text', '')
        if 'fg' in kw:
            fg = kw.pop('fg')
        else:
            fg = kw.pop('foreground', 'black')
        # initialize the canvas
        tk.Canvas.__init__(self, master, **kw)
        # display the text
        self.create_text(2, 2, anchor='nw', font=font, text=text, fill=fg, tags='text')
        h = font.metrics('linespace')  # font property needed to position correctly the underlining
        bbox = self.bbox('text')   # get text bounding box in the canvas
        w = font.actual('size')//8 # scale thickness of the underlining with fontsize
        # create the double underlining 
        self.create_line(bbox[0], h - 1, bbox[2], h - 1, fill=fg, width=w, tags='line')
        self.create_line(bbox[0], h + int(1.1*w), bbox[2], h + int(1.1*w), fill=fg, width=w, tags='line')
        # resize the canvas to fit the text
        bbox = self.bbox('all')
        self.configure(width=bbox[2], height=bbox[3])

root = tk.Tk()
for size in [8, 16, 32, 64]:
    DblUnderlineLabel(root, text="Arial %i bold" % size, font="Arial %i bold" % size).pack()
root.mainloop()    

文本示例: screenshot

相关问题 更多 >

    热门问题