如何在 Tkinter 的文字框中插入文字?


Tkinter 支援兩種型別的文字編輯器——Entry 小部件和 Text 小部件。Tkinter 文字小部件用於建立文字編輯器,可以在其中編輯、新增或刪除文字。我們可以使用 Text(parent) 建構函式建立文字小部件。為了為文字小部件插入預設文字,我們可以在文字小部件聲明後使用 insert(INSERT, "text_to_insert")insert("1.0", "text_to_insert") 方法。

示例

在此示例中,我們將文字插入文字框的開頭。

#Import the required Libraries
from tkinter import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry of tkinter frame
win.geometry("750x250")

#Create a Text Box
text= Text(win, width= 50, height= 30, background=
"gray71",foreground="#fff",font= ('Sans Serif', 13, 'italic bold'))

#Insert the text at the begining
text.insert(INSERT, "Write Something About Yourself")
text.pack(expand= 1, fill= BOTH)

win.mainloop()

輸出

執行以上程式碼,在視窗中顯示文字框。

在給定的輸出中,預設文字最初設定在文字框的開頭。

更新日期:2021 年 5 月 4 日

11K+ 瀏覽

開啟您的 職業

完成該課程以獲得認證

開始
廣告
© . All rights reserved.