Text多行文本框詳解
Text多行文本框主要用於顯示多行文本, 還可以顯示網頁鏈接, 圖片, HTML頁面, 甚至CSS樣式表, 添加組件等. 因此, 也被當做簡單的文本處理器, 文本編輯器或者網頁瀏覽器來使用. 比如:IDLE就是Text組件構成的.
1 # coding:utf-8 2 from tkinter import * 3 import webbrowser 4 5 6 class Application(Frame): 7 """一個經典的GUI程序類寫法""" 8 def __init__(self, master=None): 9 super().__init__(master) # super代表的是父類的定義,而不是父類的對象 10 self.master = master 11 self.pack() 12 self.createWidget() 13 14 def createWidget(self): 15 """創建登錄界面組件""" 16 self.w1 = Text(root, width=40, height=12, bg='gray') 17 self.w1.pack() 18 self.w1.insert(1.0, '123456789\nabcdefg') 19 self.w1.insert(2.3, 'ooooooooooooooooo') 20 21 22 Button(self, text='重復插入文本', command=self.insertText).pack(side='left') 23 Button(self, text='返回文本', command=self.returnText).pack(side='left') 24 Button(self, text='插入圖片', command=self.addImage).pack(side='left') 25 Button(self, text='添加組件', command=self.addWidget).pack(side='left') 26 Button(self, text='通過tag精確控制文本', command=self.testTag).pack(side='left') 27 28 29 def insertText(self): 30 # INSERT索引表示在光標處插入 31 self.w1.insert(INSERT, 'Xujie') 32 # END索引表示在最后插入 33 self.w1.insert(END, 'Liran') 34 self.w1.insert(1.2, 'Xujie') 35 36 37 def returnText(self): 38 # Indexes索引用來指向Text組件中文本配置, Text組件索引也是對應實際字符之間的位置 39 #核心:行號從1開始, 列號從零開始 40 print(self.w1.get(1.2, 1.6)) 41 print('所有文本內容\n'+self.w1.get(1.0, END)) 42 43 44 def addImage(self): 45 self.photo = PhotoImage(file='1/little_pic.gif') 46 self.w1.image_create(END, image=self.photo) 47 48 49 def addWidget(self): 50 b1 = Button(self.w1, text='愛liran') 51 # 在text組件中創建命令 52 self.w1.window_create(INSERT, window=b1) 53 54 55 def testTag(self): 56 self.w1.delete(1.0, END) 57 self.w1.insert(INSERT, 'good good study, day day up!\n百度搜索') 58 self.w1.tag_add('good', 1.0, 1.9) 59 self.w1.tag_config('good', background='red',foreground='yellow') 60 self.w1.tag_add('baidu', 2.0, 2.2) 61 self.w1.tag_config('baidu', underline=True) 62 self.w1.tag_bind('baidu', '<Button-1>', self.webshow) 63 64 65 def webshow(self, event): 66 webbrowser.open('http://www.baidu.com') 67 68 69 70 if __name__ == "__main__": 71 root = Tk() 72 root.geometry("400x450+200+300") 73 root.title('測試') 74 app = Application(master=root) 75 root.mainloop()
