traitsui 庫互動式界面
Item對象屬性
Item(id,name,label…)
屬性 說明id item的唯一id
name trait屬性的名稱label 靜態文本,用於顯示編輯器的標籤tooltip 編輯器的提示文本view對象屬性
View(title,width,height,resizable…)n屬性 說明ntitle 窗口標題欄nWidth 窗口寬度nHeight 窗口高度nresizable 窗口大小可變,默認為Truennfrom traits.api import HasTraits, Str, Intnfrom traitsui.api import View, Itemnnclass ModelManager(HasTraits):nmodel_name = Strncategory = Strnmodel_file = Strnmodel_number = Intnnview = View(nItem(model_name, label=u"模型名稱"),nItem(model_file, label=u"文件名"),nItem(category, label=u"模型類型"),nItem(model_number,label=u"模型數量"),ntitle = u"模型資料", width=220, resizable = True) nnmodel = ModelManager()nmodel.configure_traits()n
Group對象
from traitsui.api import GroupGroup(…)屬性 說明
orientation 編輯器的排列方向layout 布局方式normal、flow、split、tabbedshow_labels 是否顯示編輯器的標籤columns 布局的列數,範圍為(1,50)from traits.api import HasTraits, Str, Intnfrom traitsui.api import View, Item, Groupnfrom traitsui.menu import ModalButtonsnnclass ModelManager(HasTraits):n model_name = Strn category = Strn model_file = Strn model_number = Intn vertices = Intnnview1 = View(n Group(n Group(n Item(model_name, label=u"模型名稱"),n Item(model_file, label=u"文件名"),n Item(category, label=u"模型類型"),n label = u模型信息,n show_border = True),n Group(n Item(model_number,label=u"模型數量"),n Item(vertices,label=u"頂點數量"),n label = u統計數據,n show_border = True),n orientation=horizontal),n kind = modal,n buttons = ModalButtonsnn)nnmodel = ModelManager()nmodel.configure_traits(view=view1)n
from traits.api import HasTraits, Int, Range, Property, property_depends_onnfrom traitsui.api import View, Item, RangeEditornnclass RangeDemo(HasTraits):n a = Range(1, 10)n b = Range(1, 10)n c = Property(Int)n view = View(n Item(a),n Item(b),n _,n Item(c,editor=RangeEditor(low = 1, high = 20, mode = slider)),n Item(c),n width = 0.3n )nn @property_depends_on(a,b, settable = True)n def _get_c(self):n print("computing")n return (self.a + self.b)nnran = RangeDemo()nran.edit_traits()n
from traits.api import HasTraits, Str, Passwordnfrom traitsui.api import Item, Group, Viewnnclass TextEditor(HasTraits):n# 定義文本編輯器的變數nstring_trait = Str("sample string")npassword = Passwordn# 定義布局ntext_str_group = Group(nItem(string_trait, style = simple, label= Simple),nItem(_),nItem(string_trait, style = custom, label= Custom),nItem(_),nItem(password, style = simple, label= password)n)n# 定義視圖ntraits_view = View(ntext_str_group,ntitle = TextEditor,nbuttons = [OK]n)nntext = TextEditor()ntext.configure_traits()n
"""n演示TraitsUI的各種編輯器n"""nnimport osnfrom datetime import timenfrom traits.api import *nfrom traitsui.api import *nnclass EditorDemoItem(HasTraits):n """界面右半部分,對於選中的某個Trait屬性,使用4種樣式創建屬性編輯器"""n code = Code()n view = View(n Group(n # 使用simple編輯器,可盡量減少界面佔用空間,width屬性可指定編輯器寬度,負數表示強制設置寬度n Item("item", style="simple", label="simple", width=-300),n "_", # 下劃線字元串表示創建分隔線n # 使用custom編輯器,可盡量呈現更多內容 #n # TODO: Trait,Enum,Range三個函數無法用於custom編輯器,要運行這三個函數需要將其注釋n Item("item", style="custom", label="custom"),n "_",n # 使用text編輯器,只呈現文本內容n Item("item", style="text", label="text"),n "_",n # 使用readonly編輯器,呈現只讀文本n Item("item", style="readonly", label="readonly"),n ),n )nnnclass EditorDemo(HasTraits):n """創建主界面"""n codes = List(Str) # 創建List界面,用來展示各種Trait屬性的字元串n selected_item = Instance(EditorDemoItem) # 初始化selected_item界面,用來存儲被選項的編輯界面n selected_code = Str # 初始化selected_code變數,用來存儲被選項名稱n view = View(n # 使用HSplite水平分隔兩個界面n HSplit(n # 界面左半部分,用來創建各種Trait屬性的源程序列表n Item("codes", style="custom", show_label=False,n # 將editor屬性設置為ListStrEditor(列表選擇框控制項),並更新selected_code變數n editor=ListStrEditor(editable=False, selected="selected_code")),n # 界面右半部分n Item("selected_item", style="custom", show_label=False),n ),n resizable=True,n width=800,n height=400,n title=u"各種編輯器演示"n )nn def _selected_code_changed(self):n """當selected_code變數改變時觸發,更新selected_item界面"""n item = EditorDemoItem(code=self.selected_code)n # 使用eval對selected_code字元串進行求值,並將值存儲到item中n item.add_trait("item", eval(str(self.selected_code)))n self.selected_item = itemnnnclass Employee(HasTraits):n """創建Employee類,該類為包含四個屬性的界面"""n name = Unicode(label=u"姓名")n department = Unicode(label=u"部門")n salary = Int(label=u"薪水")n bonus = Int(label=u"獎金")n view = View("name", "department", "salary", "bonus")nnnif __name__ == __main__:n employee = Employee()n demo_list = [u"低通", u"高通", u"帶通", u"帶阻"]n trait_defines = """n Array(dtype="int32", shape=(3,3)) #{1}fadsfan Bool(True)n Button("Click me")n List(editor=CheckListEditor(values=demo_list))n Code("print(hello world)")n Color("red")n RGBColor("red")n Trait(*demo_list) #無法用於custom編輯器n Directory(os.getcwd())n Enum(*demo_list) #無法用於custom編輯器n File()n Font()n HTML(<b><font color="red" size="40">hello world</font></b>)n List(Str, demo_list)n Range(1, 10, 5) #無法用於custom編輯器n List(editor=SetEditor(values=demo_list))n List(demo_list, editor=ListStrEditor())n Str("hello")n Password("hello")n Str("Hello", editor=TitleEditor())n Tuple(Color("red"), Range(1,4), Str("hello"))n Instance(EditorDemoItem, employee) n Instance(EditorDemoItem, employee, editor=ValueEditor())n Instance(time, time(), editor=TimeEditor())n """n demo = EditorDemo()n # 一般寫法n trait_list = []n for s in trait_defines.split(n): # 按行分割字元串n if s.split(#)[0].strip(): # 判斷s中是否存在可執行函數n trait_list.append(s.split(#)[0]) # 去掉注釋ndemo.codes is coming soon = trait_listn # 簡潔寫法n # demo.codes is coming soon = [s.split("#")[0] for s in trait_defines.split("n") if s.split(#)[0].strip()]n demo.configure_traits()n
推薦閱讀:
※怎樣才算精通Python?
※pycharm和eclipse+pydev的對比?
※Python數據分析及可視化實例之Pandas函數速查表
※關於爬蟲的HTTP原理,看完這一長篇就夠了!(附三大爬蟲案例)
TAG:Python |