1. 程式人生 > 實用技巧 >Python20-02_GUI程式設計----Text多行文字框詳解

Python20-02_GUI程式設計----Text多行文字框詳解

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()