src_templates.py


directory : D:\2018_py_proj\TkGridGUI\tkgridgui
Line Count : 618
Line Clip Size : No Clipping

tab_of_notebook_changed  Word MatchCase (0) 
1 #!/usr/bin/env python 2 # -*- coding: ascii -*- 3 from __future__ import print_function 4 from __future__ import unicode_literals 5 6 from builtins import str 7 import sys 8 9 import copy 10 11 letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 12 digits = '0123456789' 13 14 # change all non-legal letters to underscore 15 goodset = str(letters+digits+'_') 16 17 def legal_char( c ): 18 if c in goodset: 19 return c 20 else: 21 return '_' 22 23 def legalPythonIdentifier( name ): 24 name = str(name) 25 #legalName = name.translate(legalTranTab) 26 legalName = ''.join( [legal_char(c) for c in name] ) 27 28 if legalName: 29 if legalName[0] in digits: 30 legalName = 'x'+legalName 31 32 return legalName 33 34 def legalQuotedString( s ): # precede any quotes with backslash 35 val = str(s) 36 val = val.replace("'","\\'") 37 val = val.replace('"','\\"') 38 return val 39 40 def legalWidgetName(name, ctype): 41 lcname = name#.lower() 42 lctype = ctype#.lower() 43 44 if lcname.find( lctype ) > -1: 45 legalName = lcname#.title() 46 else: 47 #legalName = '%s_%s'%(lcname.title(), lctype.title()) 48 legalName = '%s_%s'%(lcname, lctype) 49 50 legalName = legalPythonIdentifier(legalName) 51 52 return legalName 53 54 def makeOptionString( opDict, startComma=1 ): 55 if opDict: 56 sL = [] 57 for k,v in list(opDict.items()): 58 # precede any quotes in the value with a backslash 59 val = legalQuotedString(v) 60 sL.append( '%s="%s"'%(k,val) ) 61 s = ', '.join(sL) 62 if len(s)>0 and startComma: 63 s = ', ' + s 64 else: 65 s = '' 66 67 return s 68 69 70 sInit = '''class %s: 71 def __init__(self, master): 72 73 grid_frame = Frame( master %s) 74 self.grid_frame = grid_frame 75 grid_frame.pack(expand=1, fill=BOTH) 76 self.master = master 77 78 self.x, self.y, self.w, self.h = %i, %i, %i, %i 79 ''' 80 def beginSourceFile(className, width=300, height=300, opDict=None, x=10, y=10): 81 return sInit%(className, makeOptionString( opDict ), x, y, width, height) 82 #return sInit%(className.title(), makeOptionString( opDict ), x, y, width, height) 83 84 #------------------------------------------------------------- 85 sHideOkBtn = ''' 86 def buttonbox(self): 87 pass 88 # this dummy routine overrides the standard "OK" and "Cancel" buttons 89 # REMEMBER!!! to call self.ok() and self.cancel() in User Code 90 ''' 91 92 sInitDialog = ''' 93 if sys.version_info < (3,): 94 from tkSimpleDialog import Dialog 95 else: 96 from tkinter.simpledialog import Dialog 97 98 class _Dialog(Dialog): 99 # use dialogOptions dictionary to set any values in the dialog 100 def __init__(self, parent, title = None, dialogOptions=None): 101 102 self.dialogOptions = dialogOptions 103 Dialog.__init__(self, parent, title) 104 105 class %s(_Dialog): 106 %s 107 def body(self, master): 108 dialogframe = Frame(master, width=%i, height=%i%s) 109 self.dialogframe = dialogframe 110 dialogframe.pack() 111 ''' 112 def beginDialogSourceFile(className, hideOkBtn, width=300, height=300, opDict=None): 113 if hideOkBtn: 114 s = sHideOkBtn 115 else: 116 s = '' 117 return sInitDialog%(className,s, width, height, makeOptionString( opDict )) 118 #return sInitDialog%(className.title(),s, width, height, makeOptionString( opDict )) 119 120 #------------------------------------------------------------- 121 sDialogValidate = ''' def validate(self): 122 self.result = {} # return a dictionary of results 123 ''' 124 def getDialogValidate(): 125 return sDialogValidate 126 #------------------------------------------------------------- 127 sEnd = ''' 128 def main(): 129 root = Tk() 130 app = %s(root) 131 root.mainloop() 132 133 if __name__ == '__main__': 134 main() 135 ''' 136 def endSourceFile(className): 137 return sEnd%(className,) 138 #return sEnd%(className.title(),) 139 140 #------------------------------------------------------------- 141 sEndDialog = ''' 142 143 def apply(self): 144 print( 'apply called' ) 145 146 class _Testdialog: 147 def __init__(self, master): 148 frame = Frame(master, width=300, height=300) 149 frame.pack() 150 self.master = master 151 self.x, self.y, self.w, self.h = -1,-1,-1,-1 152 153 self.Button_1 = Button(text="Test Dialog", relief="raised", width="15") 154 self.Button_1.place(x=84, y=36) 155 self.Button_1.bind("<ButtonRelease-1>", self.Button_1_Click) 156 157 def Button_1_Click(self, event): #click method for component ID=1 158 dialog = %s(self.master, "Test Dialog") 159 print( '===============Result from Dialog====================' ) 160 print( dialog.result ) 161 print( '=====================================================' ) 162 163 def main(): 164 root = Tk() 165 app = _Testdialog(root) 166 root.mainloop() 167 168 if __name__ == '__main__': 169 main() 170 ''' 171 def endDialogSourceFile(className): 172 return sEndDialog%(className,) 173 #return sEndDialog%(className.title(),) 174 #---------------------------------------------------------------- 175 # create weight statements: columnconfigure(col, weight=wt) and rowconfigure(row, weight=wt) 176 177 def createWeightStatement(guiType, parent_frame, is_row, rc_val, wt): 178 179 if guiType=='dialog': 180 master = 'self.dialogframe' 181 else: 182 if parent_frame=="Main": 183 master = 'self.grid_frame' 184 else: 185 master = 'self.'+parent_frame 186 187 if is_row: 188 return " %s.rowconfigure(%s, weight=%s)\n"%(master, rc_val, wt) 189 else: 190 return " %s.columnconfigure(%s, weight=%s)\n"%(master, rc_val, wt) 191 192 #---------------------------------------------------------------- 193 # create list box... needs special treatment for y scroller 194 sCreateWidgetWScroll_Y=''' 195 lbframe = Frame( {master} ) 196 self.{wName}_frame = lbframe 197 vbar=Scrollbar(lbframe, orient=VERTICAL) 198 self.{wName} = {widget_type}(lbframe, {opStr} yscrollcommand=vbar.set) 199 vbar.config(command=self.{wName}.yview) 200 201 vbar.grid(row=0, column=1, sticky='ns') 202 self.{wName}.grid(row=0, column=0) 203 ''' 204 205 sCreateWidgetWScroll_X=''' 206 lbframe = Frame( {master} ) 207 self.{wName}_frame = lbframe 208 hbar=Scrollbar(lbframe, orient=HORIZONTAL) 209 self.{wName} = {widget_type}(lbframe, {opStr} xscrollcommand=hbar.set) 210 hbar.config(command=self.{wName}.xview) 211 self.{wName}.config( wrap=NONE ) # x scroll implies no wrap 212 213 hbar.grid(row=1, column=0, sticky='ew') 214 self.{wName}.grid(row=0, column=0) 215 ''' 216 217 sCreateWidgetWScroll_XY=''' 218 lbframe = Frame( {master} ) 219 self.{wName}_frame = lbframe 220 vbar=Scrollbar(lbframe, orient=VERTICAL) 221 hbar=Scrollbar(lbframe, orient=HORIZONTAL) 222 223 self.{wName} = {widget_type}(lbframe, {opStr} xscrollcommand=hbar.set, yscrollcommand=vbar.set) 224 hbar.config(command=self.{wName}.xview) 225 vbar.config(command=self.{wName}.yview) 226 self.{wName}.config( wrap=NONE ) # x scroll implies no wrap 227 228 hbar.grid(row=1, column=0, sticky='ew') 229 vbar.grid(row=0, column=1, sticky='ns') 230 self.{wName}.grid(row=0, column=0) 231 ''' 232 233 sCreateWidgetWOScroll=''' 234 self.%s = %s(%s, %s) 235 ''' 236 def createWidgetwName(wName, widget_type, guiType, parent_frame, opDict=None): 237 238 if opDict is None: 239 myOpDict = {} 240 else: 241 myOpDict = copy.deepcopy( opDict ) 242 243 def remove_option( op_name ): 244 if op_name in myOpDict: 245 del( myOpDict[op_name] ) 246 247 remove_option("docstring") 248 if guiType=='dialog': 249 master = 'self.dialogframe' 250 else: 251 if parent_frame=="Main": 252 master = 'self.grid_frame' 253 else: 254 master = 'self.'+parent_frame 255 256 doscroll = 0 257 if myOpDict: 258 if 'scrolly' in myOpDict: 259 if myOpDict['scrolly'].lower()=='yes': 260 doscroll += 1 261 remove_option('scrolly') 262 263 if 'scrollx' in myOpDict: 264 if myOpDict['scrollx'].lower()=='yes': 265 doscroll += 2 266 remove_option('scrollx') 267 268 opStr = makeOptionString( myOpDict, startComma=0 ) 269 if opStr: 270 opStr += ',' 271 272 if doscroll: 273 if doscroll == 1: 274 return sCreateWidgetWScroll_Y.format(master=master,wName=wName, widget_type=widget_type, opStr=opStr) 275 elif doscroll == 2: 276 return sCreateWidgetWScroll_X.format(master=master,wName=wName, widget_type=widget_type, opStr=opStr) 277 else: 278 return sCreateWidgetWScroll_XY.format(master=master,wName=wName, widget_type=widget_type, opStr=opStr) 279 280 else: 281 return sCreateWidgetWOScroll%( wName, widget_type, master, opStr) 282 #return sCreateWidgetWOScroll%( wName, widget_type.title(), master, opStr) 283 #---------------------------------------------------------------- 284 285 # create widget 286 # self.<name> = <widget>( <options> ) 287 sCreateWidget = ' self.%s = %s( %s %s)\n' 288 def createWidget(wName, widget_type, guiType, parent_frame, opDict=None): 289 290 if opDict is None: 291 myOpDict = {} 292 else: 293 myOpDict = copy.deepcopy( opDict ) 294 295 def remove_option( op_name ): 296 if op_name in myOpDict: 297 del( myOpDict[op_name] ) 298 299 remove_option("docstring") 300 remove_option("columnspan") 301 remove_option("rowspan") 302 303 remove_option("row_weights") 304 remove_option("col_weights") 305 remove_option("tab_labels") 306 307 if widget_type.lower() in ('entry','text','listbox','frame'): 308 remove_option('text') 309 310 # the ttk widgets can't accept style inputs 311 if widget_type.lower() in ('combobox', 'progressbar', 'separator', 'treeview', 'notebook', 'optionmenu'): 312 remove_option('width') 313 remove_option('height') 314 remove_option('background') 315 316 if widget_type.lower() =='combobox': 317 remove_option('selection') 318 319 if widget_type.lower() in ('frame','labelframe','notebook','radiogroup'): 320 remove_option('row_weights') 321 remove_option('col_weights') 322 323 # sticky option belongs in .grid statement 324 if 'sticky' in myOpDict: 325 del(myOpDict['sticky']) # delete from copy of original dictionary 326 327 #print("widget_type =",widget_type) 328 #if widget_type.lower()=='labelframe': 329 # Constructor = 'LabelFrame' 330 #else: 331 Constructor = widget_type#.title() 332 333 doscroll = 0 334 if myOpDict: 335 if 'scrolly' in myOpDict: 336 if (myOpDict['scrolly'].lower()=='yes'): 337 doscroll = 1 338 if 'scrollx' in myOpDict: 339 if (myOpDict['scrollx'].lower()=='yes'): 340 doscroll = 1 341 #remove_option('scrolly') 342 # scrolly is a "special" option 343 #if myOpDict.has_key('scrolly'): 344 # del(myOpDict['scrolly']) # delete from copy of original dictionary 345 346 if doscroll: 347 return createWidgetwName(wName, widget_type, guiType, parent_frame, myOpDict) 348 else: 349 remove_option('scrolly') 350 remove_option("scrollx") 351 352 if guiType=='dialog': 353 return sCreateWidget%(wName, Constructor,'frame', makeOptionString( myOpDict, startComma=1 )) 354 else: 355 if parent_frame=="Main": 356 return sCreateWidget%(wName, Constructor,'self.grid_frame', makeOptionString( myOpDict, startComma=1 )) 357 else: 358 return sCreateWidget%(wName, Constructor, 'self.'+parent_frame, makeOptionString( myOpDict, startComma=1 )) 359 360 #---------------------------------------------------------------- 361 362 # place widget into grid 363 # self.<name>.grid( row=<x>, column=<y> ) 364 sGridWidget = ' self.%s.grid(row=%i, column=%i)\n' 365 sGridWidgetFrame = ' self.%s_frame.grid(row=%i, column=%i)\n' 366 #def gridWidget(wName, ctype, row, col, is_gridWidgetFrame, sticky=''): 367 def gridWidget(wName, row, col, is_gridWidgetFrame, sticky='', rowspan='', columnspan=''): 368 369 #print("In gridWidget, wName=%s, ctype=%s, row=%s, col=%s, is_gridWidgetFrame=%s, sticky=%s"%\ 370 # (wName, ctype, row, col, is_gridWidgetFrame, sticky)) 371 372 if is_gridWidgetFrame: 373 s = sGridWidgetFrame%(wName, int(row), int(col)) 374 else: 375 s = sGridWidget%(wName, int(row), int(col)) 376 377 if sticky: 378 s = s.replace( ')',', sticky="%s")'%sticky ) 379 380 if rowspan: 381 s = s.replace( ')',', rowspan="%s")'%rowspan ) 382 383 if columnspan: 384 s = s.replace( ')',', columnspan="%s")'%columnspan ) 385 386 #print( " s =",s ) 387 return s 388 389 #---------------------------------------------------------------- 390 # bind widget 391 # self.<name>.bind("<event>", self.<callback>) 392 sBindWidget = ' self.%s.bind("<%s>", self.%s)\n' 393 def bindWidget(wName, eventName, callBack): 394 return sBindWidget%( wName, eventName, callBack) 395 #---------------------------------------------------------------- 396 # make string variable 397 # self.<name>_StringVar = StringVar() 398 sMakeStringVar = ' self.%s_StringVar = StringVar()\n' 399 def makeStringVar( wName ): 400 return sMakeStringVar%wName 401 402 #---------------------------------------------------------------- 403 # connect string variable to widget 404 # self.<name>.configure(variable=self.<name>_StringVar, <options>) 405 sConnectStringVar = ' self.%s.configure(variable=self.%s_StringVar%s)\n' 406 def connectStringVar(wName, opDict=None): 407 return sConnectStringVar%(wName, wName, makeOptionString( opDict )) 408 409 # special for Entry widget 410 sConnectEntryStringVar = ' self.%s.configure(textvariable=self.%s_StringVar%s)\n' 411 def connectEntryStringVar(wName, opDict=None): 412 return sConnectEntryStringVar%(wName, wName, makeOptionString( opDict )) 413 #---------------------------------------------------------------- 414 # turn on trace for string variable 415 # self.<name>_StringVar_traceName = self.<name>_StringVar.trace_variable("w", self.<name>_StringVar_Callback) 416 sTraceStringVar = ' self.%s_StringVar_traceName = self.%s_StringVar.trace_variable("w", self.%s_StringVar_Callback)\n' 417 def traceStringVar(wName): 418 return sTraceStringVar%(wName, wName, wName) 419 #---------------------------------------------------------------- 420 # statusbar 421 sStatusBar = ''' 422 # make a Status Bar 423 self.statusMessage = StringVar() 424 self.statusMessage.set("") 425 self.statusbar = Label(self.master, textvariable=self.statusMessage, bd=1, relief=SUNKEN) 426 self.statusbar.pack(anchor=SW, fill=X, side=BOTTOM) 427 ''' 428 def getStatusBarSource(): 429 return sStatusBar 430 431 sStatusBarDialog = ''' 432 # make a Status Bar 433 self.statusMessage = StringVar() 434 self.statusMessage.set("") 435 self.statusbar = Label(self.dialogframe, textvariable=self.statusMessage, bd=1, relief=SUNKEN) 436 self.statusbar.grid(row=99, column=0, columnspan=99, sticky='ew') 437 ''' 438 def getDialogStatusBarSource(): 439 return sStatusBarDialog 440 441 #---------------------------------------------------------------- 442 # standard message dialogs 443 sMessageDialogs = ''' 444 # standard message dialogs... showinfo, showwarning, showerror 445 def ShowInfo(self, title='Title', message='your message here.'): 446 tkinter.messagebox.showinfo( title, message ) 447 return 448 def ShowWarning(self, title='Title', message='your message here.'): 449 tkinter.messagebox.showwarning( title, message ) 450 return 451 def ShowError(self, title='Title', message='your message here.'): 452 tkinter.messagebox.showerror( title, message ) 453 return 454 455 # standard question dialogs... askquestion, askokcancel, askyesno, or askretrycancel 456 # return True for OK, Yes, Retry, False for Cancel or No 457 def AskYesNo(self, title='Title', message='your question here.'): 458 return tkinter.messagebox.askyesno( title, message ) 459 def AskOK_Cancel(self, title='Title', message='your question here.'): 460 return tkinter.messagebox.askokcancel( title, message ) 461 def AskRetryCancel(self, title='Title', message='your question here.'): 462 return tkinter.messagebox.askretrycancel( title, message ) 463 464 # return "yes" for Yes, "no" for No 465 def AskQuestion(self, title='Title', message='your question here.'): 466 return tkinter.messagebox.askquestion( title, message ) 467 # END of standard message dialogs 468 ''' 469 def getStandardMessageDialogs(): 470 return sMessageDialogs 471 #---------------------------------------------------------------- 472 sFileDialogs = ''' # standard file dialogs... askdirectory, askopenfile, asksaveasfilename 473 474 # return a string containing directory name 475 def AskDirectory(self, title='Choose Directory', initialdir="."): 476 dirname = tkinter.filedialog.askdirectory(parent=%s,initialdir=initialdir,title=title) 477 return dirname # <-- string 478 479 # return an OPEN file type object OR None (opened using mode, 'r','rb','w','wb') 480 # WARNING... opening file with mode 'w' or 'wb' will erase contents 481 def AskOpenFile(self, title='Choose File', mode='rb', initialdir='.', filetypes=None): 482 if filetypes==None: 483 filetypes = [ 484 ('Text File','*.txt'), 485 ('Data File','*.dat'), 486 ('Output File','*.out'), 487 ('Any File','*.*')] 488 fileobj = tkinter.filedialog.askopenfile(parent=%s,mode=mode,title=title, 489 initialdir=initialdir, filetypes=filetypes) 490 491 # if opened, then fileobj.name contains the name string 492 return fileobj # <-- an opened file, or the value None 493 494 # return a string containing file name (the calling routine will need to open the file) 495 def AskSaveasFilename(self, title='Save File', filetypes=None, initialfile=''): 496 if filetypes==None: 497 filetypes = [ 498 ('Text File','*.txt'), 499 ('Data File','*.dat'), 500 ('Output File','*.out'), 501 ('Any File','*.*')] 502 503 fileName = tkinter.filedialog.asksaveasfilename(parent=%s,filetypes=filetypes, initialfile=initialfile ,title=title) 504 return fileName # <-- string 505 506 # END of standard file dialogs 507 ''' 508 def getStandardFileDialogs(guiType='main'): 509 if guiType=='dialog': 510 master = 'self' 511 else: 512 master = 'self.master' 513 514 return sFileDialogs%(master, master, master) 515 #---------------------------------------------------------------- 516 sColorDialog=''' 517 # returns a color tuple and a string representation of the selected color 518 def AskForColor(self,title='Pick Color'): 519 ctuple,cstr = tkinter.colorchooser.askcolor(title=title) 520 return ctuple,cstr 521 ''' 522 def getStandardColorDialog(): 523 return sColorDialog 524 #---------------------------------------------------------------- 525 #---------------------------------------------------------------- 526 sAlarmDialog=''' 527 # alarm function is called after specified number of milliseconds 528 def SetAlarm(self, milliseconds=1000): 529 self.master.after( milliseconds, self.Alarm ) 530 def Alarm(self): 531 pass 532 ''' 533 def getStandardAlarmDialog(): 534 return sAlarmDialog 535 #---------------------------------------------------------------- 536 sTopImports=''' 537 538 from __future__ import unicode_literals 539 from future import standard_library 540 standard_library.install_aliases() 541 from builtins import str 542 from builtins import range 543 from builtins import object 544 545 from tkinter.ttk import Combobox, Progressbar, Separator, Treeview, Notebook%s 546 547 from tkinter import * 548 from tkinter import Button, Canvas, Checkbutton, Entry, Frame, Label, LabelFrame 549 from tkinter import Listbox, Message, Radiobutton, Spinbox, Text 550 from tkinter import OptionMenu 551 import tkinter.filedialog 552 from tkinter import _setit as set_command 553 554 ''' 555 556 sDialogImport = '''try: 557 from tkSimpleDialog import Dialog 558 except: 559 from tkinter.simpledialog import Dialog 560 ''' 561 def get_top_imports( incMsgBox, incDialog, incColorCh): 562 #py2L = [] 563 py3L = [] 564 if incMsgBox: 565 #py2L.append(' import tkMessageBox') 566 py3L.append('import tkinter.messagebox') 567 if incDialog: 568 #py2L.append(' from tkSimpleDialog import Dialog') 569 py3L.append( sDialogImport ) 570 if incColorCh: 571 #py2L.append(' import tkColorChooser') 572 py3L.append('import tkinter.colorchooser') 573 574 if py3L: 575 #spy2 = '\n' + '\n'.join(py2L) 576 spy3 = '\n' + '\n'.join(py3L) 577 else: 578 #spy2 = '' 579 spy3 = '' 580 581 return sTopImports%( spy3 ) 582 583 #---------------------------------------------------------------- 584 585 if __name__ == '__main__': 586 if 1: 587 print( beginSourceFile("TestForm1") ) 588 print( beginSourceFile("TestForm2",opDict={'background':'yellow'}) ) 589 590 print() 591 print( endSourceFile("TestForm1") ) 592 593 print() 594 print( createWidget('Bang_Checkbutton', 'Checkbutton', 'Checkbutton', 'Main', {'bg':'red', 'ddd':'aaa'}) ) 595 596 print() 597 print( gridWidget('Bang_Checkbutton', '22', '55', 0) ) 598 599 print() 600 print( bindWidget('Bang_Button', 'ButtonRelease-1', 'Bang_Button_Click') ) 601 602 print() 603 print( makeStringVar( 'Bang_Checkbutton' ) ) 604 605 print() 606 print( connectStringVar('Bang_Checkbutton', opDict={'onvalue':"yes", 'offvalue':"no"}) ) 607 608 print() 609 print( traceStringVar('Bang_Checkbutton') ) 610 print() 611 print( createWidget('myList', 'Listbox', 'Listbox', 'Frame_1', {'bg':'red', 'ddd':'aaa'}) ) 612 613 print() 614 print( gridWidget('myList', '22', '55', 1) ) 615 616 print() 617 print( gridWidget('myList', '22', '55', 1, sticky='ew') ) 618 619