tkinter文字框小功能(3) 分割線

2021-10-23 12:14:48 字數 3137 閱讀 4029

結語在文字渲染中,各種不同內容最好的分界方式,就是使用分割線,分割線能讓讀者更加清楚地閱讀文字。因此,在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創新☀

tkinter基礎 輸入框 文字框

了解輸入框 文字框的使用方法 利用1製作簡易介面 首先明確上面由幾個元素組成 該介面由介面標題,輸入框 兩個按鈕 文字框組成。該介面我們需要實現的功能 實現 1 import tkinter as tk2 3 windows tk.tk 4 windows.title 輸入框 文字框 5 windo...

Hello專案功能測試 文字框

必填項空輸入,應提示錯誤 必填項只輸入若干個空格,應提示錯誤 輸入最小字元數 1 輸入最小字元數 輸入最大字元數 1 輸入最大字元數 輸入最大字元數 1 輸入是否允許回車換行 儲存後再顯示,是否能保持輸入時的格式 僅輸入回車換行,檢查能否正確儲存 若能,檢視儲存結果 若不能,是否有正確提示。僅輸入空...

vb取消文字框的貼上功能

以下 在窗體 程式 option explicit 石陸軟體屋 private sub form load g holdproc setwindowlong text1.hwnd,gwl wndproc,addressof wndproc end sub private sub form unloa...