在文本渲染中,各种不同内容最好的分界方式,就是使用分割线,分割线能让读者更加清楚地阅读文本。因此,在tkinter的文本框组件中,我们也要实现分割线。
相信很多人看到上面那句就直接走开了————tkinter不是有ttk.Separator吗,直接在文本框使用 window_create(…) 不就完事了吗?别急。如果真的直接在文本框插入分割线的话,那么文本框会显示一个2像素左右的灰点,那个就是分割线,不信,自己可以试一下。
那是因为文本框组件导入分割线时会控制组件大小适应,分割线内部不含组件,所有就被缩得很小。因此,必须使用一些能够自定义大小的组件,画布当然是首选。为了丰富分割线样式,我们不再使用分割组件,而是直接绘图。
通过继承画布类,则可以在文本框中插入分割线
class TextSeparat(Canvas):#继承画布Canvas
'''
用于在tkinter文本框插入不同颜色、样式的分割线
'''
def __init__(self,text,width,bg='white',color='#8cfefa',line='common'):
#消除互补外框,使画布宽度等于分割线宽度
super().__init__(text,width=width,height=8,background=bg,highlightthickness=0,relief='flat',bd=0)
"""
text:要插入分割线的文本框
width:分割线宽度
bg:背景色,一般不用
color:分割线颜色
line:分割线样式
"""
现在我们将丰富分割线的样式。
在Tin中,我使用形象化的标记来决定分割线样式:—, - -, -··, ···, ===, = =,分别对应的样式字符如下:
common,dash,dash_point,point,double_line,double_dash。
通过绘制直线的单线长度和个数,就可以实现以上的样式。
完整代码如下:
class TextSeparat(Canvas):#working
'''
用于在tkinter文本框插入不同颜色、样式的分割线
'''
def __init__(self,text,width,bg='white',color='#8cfefa',line='common'):
super().__init__(text,width=width,height=8,background=bg,highlightthickness=0,relief='flat',bd=0)
if line=='common':#---
self.create_line(0,4,width,4,fill=color,width=2)
elif line=='dash':#- -
self.create_line(0,4,width,4,fill=color,dash=(10,3),width=2)
elif line=='dash_point':#-··
self.create_line(0,4,width,4,fill=color,dash=(5,2,3),width=2)
elif line=='point':#···
self.create_line(0,4,width,4,fill=color,dash=(2,2),width=2)
elif line=='double_line':#===
self.create_line(0,3,width,3,fill=color,width=1)
self.create_line(0,6,width,6,fill=color,width=1)
elif line=='double_dash':#= =
self.create_line(0,3,width,3,fill=color,dash=(10,3),width=1)
self.create_line(0,6,width,6,fill=color,dash=(10,3),width=1)
以 common 线为例,python代码:
from tkinter import *
root=Tk()
root.geometry('500x500')
text=Text()
text.pack()
root.update()
text.window_create('end',window=TextSeparat(text,text.winfo_width(),bg=text['background'],line='common'))
root.mainloop()
在Tin中,使用
red;---
;第二个参数可以为六种形象样式字符中的任意一个
Tin知识库
除了分割线,tkinter文本框中还可以加入其它很有用的组件,丰富文本阅读。
☀tkinter创新☀