Tkinter.py 157 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857
  1. """Wrapper functions for Tcl/Tk.
  2. Tkinter provides classes which allow the display, positioning and
  3. control of widgets. Toplevel widgets are Tk and Toplevel. Other
  4. widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
  5. Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
  6. LabelFrame and PanedWindow.
  7. Properties of the widgets are specified with keyword arguments.
  8. Keyword arguments have the same name as the corresponding resource
  9. under Tk.
  10. Widgets are positioned with one of the geometry managers Place, Pack
  11. or Grid. These managers can be called with methods place, pack, grid
  12. available in every Widget.
  13. Actions are bound to events by resources (e.g. keyword argument
  14. command) or with the method bind.
  15. Example (Hello, World):
  16. import Tkinter
  17. from Tkconstants import *
  18. tk = Tkinter.Tk()
  19. frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
  20. frame.pack(fill=BOTH,expand=1)
  21. label = Tkinter.Label(frame, text="Hello, World")
  22. label.pack(fill=X, expand=1)
  23. button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
  24. button.pack(side=BOTTOM)
  25. tk.mainloop()
  26. """
  27. __version__ = "$Revision: 81008 $"
  28. import sys
  29. if sys.platform == "win32":
  30. # Attempt to configure Tcl/Tk without requiring PATH
  31. import FixTk
  32. import _tkinter # If this fails your Python may not be configured for Tk
  33. tkinter = _tkinter # b/w compat for export
  34. TclError = _tkinter.TclError
  35. from types import *
  36. from Tkconstants import *
  37. import re
  38. wantobjects = 1
  39. TkVersion = float(_tkinter.TK_VERSION)
  40. TclVersion = float(_tkinter.TCL_VERSION)
  41. READABLE = _tkinter.READABLE
  42. WRITABLE = _tkinter.WRITABLE
  43. EXCEPTION = _tkinter.EXCEPTION
  44. # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
  45. try: _tkinter.createfilehandler
  46. except AttributeError: _tkinter.createfilehandler = None
  47. try: _tkinter.deletefilehandler
  48. except AttributeError: _tkinter.deletefilehandler = None
  49. _magic_re = re.compile(r'([\\{}])')
  50. _space_re = re.compile(r'([\s])')
  51. def _join(value):
  52. """Internal function."""
  53. return ' '.join(map(_stringify, value))
  54. def _stringify(value):
  55. """Internal function."""
  56. if isinstance(value, (list, tuple)):
  57. if len(value) == 1:
  58. value = _stringify(value[0])
  59. if value[0] == '{':
  60. value = '{%s}' % value
  61. else:
  62. value = '{%s}' % _join(value)
  63. else:
  64. if isinstance(value, str):
  65. value = unicode(value, 'utf-8')
  66. elif not isinstance(value, unicode):
  67. value = str(value)
  68. if not value:
  69. value = '{}'
  70. elif _magic_re.search(value):
  71. # add '\' before special characters and spaces
  72. value = _magic_re.sub(r'\\\1', value)
  73. value = _space_re.sub(r'\\\1', value)
  74. elif value[0] == '"' or _space_re.search(value):
  75. value = '{%s}' % value
  76. return value
  77. def _flatten(tuple):
  78. """Internal function."""
  79. res = ()
  80. for item in tuple:
  81. if type(item) in (TupleType, ListType):
  82. res = res + _flatten(item)
  83. elif item is not None:
  84. res = res + (item,)
  85. return res
  86. try: _flatten = _tkinter._flatten
  87. except AttributeError: pass
  88. def _cnfmerge(cnfs):
  89. """Internal function."""
  90. if type(cnfs) is DictionaryType:
  91. return cnfs
  92. elif type(cnfs) in (NoneType, StringType):
  93. return cnfs
  94. else:
  95. cnf = {}
  96. for c in _flatten(cnfs):
  97. try:
  98. cnf.update(c)
  99. except (AttributeError, TypeError), msg:
  100. print "_cnfmerge: fallback due to:", msg
  101. for k, v in c.items():
  102. cnf[k] = v
  103. return cnf
  104. try: _cnfmerge = _tkinter._cnfmerge
  105. except AttributeError: pass
  106. def _splitdict(tk, v, cut_minus=True, conv=None):
  107. """Return a properly formatted dict built from Tcl list pairs.
  108. If cut_minus is True, the supposed '-' prefix will be removed from
  109. keys. If conv is specified, it is used to convert values.
  110. Tcl list is expected to contain an even number of elements.
  111. """
  112. t = tk.splitlist(v)
  113. if len(t) % 2:
  114. raise RuntimeError('Tcl list representing a dict is expected '
  115. 'to contain an even number of elements')
  116. it = iter(t)
  117. dict = {}
  118. for key, value in zip(it, it):
  119. key = str(key)
  120. if cut_minus and key[0] == '-':
  121. key = key[1:]
  122. if conv:
  123. value = conv(value)
  124. dict[key] = value
  125. return dict
  126. class Event:
  127. """Container for the properties of an event.
  128. Instances of this type are generated if one of the following events occurs:
  129. KeyPress, KeyRelease - for keyboard events
  130. ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
  131. Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
  132. Colormap, Gravity, Reparent, Property, Destroy, Activate,
  133. Deactivate - for window events.
  134. If a callback function for one of these events is registered
  135. using bind, bind_all, bind_class, or tag_bind, the callback is
  136. called with an Event as first argument. It will have the
  137. following attributes (in braces are the event types for which
  138. the attribute is valid):
  139. serial - serial number of event
  140. num - mouse button pressed (ButtonPress, ButtonRelease)
  141. focus - whether the window has the focus (Enter, Leave)
  142. height - height of the exposed window (Configure, Expose)
  143. width - width of the exposed window (Configure, Expose)
  144. keycode - keycode of the pressed key (KeyPress, KeyRelease)
  145. state - state of the event as a number (ButtonPress, ButtonRelease,
  146. Enter, KeyPress, KeyRelease,
  147. Leave, Motion)
  148. state - state as a string (Visibility)
  149. time - when the event occurred
  150. x - x-position of the mouse
  151. y - y-position of the mouse
  152. x_root - x-position of the mouse on the screen
  153. (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  154. y_root - y-position of the mouse on the screen
  155. (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  156. char - pressed character (KeyPress, KeyRelease)
  157. send_event - see X/Windows documentation
  158. keysym - keysym of the event as a string (KeyPress, KeyRelease)
  159. keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
  160. type - type of the event as a number
  161. widget - widget in which the event occurred
  162. delta - delta of wheel movement (MouseWheel)
  163. """
  164. pass
  165. _support_default_root = 1
  166. _default_root = None
  167. def NoDefaultRoot():
  168. """Inhibit setting of default root window.
  169. Call this function to inhibit that the first instance of
  170. Tk is used for windows without an explicit parent window.
  171. """
  172. global _support_default_root
  173. _support_default_root = 0
  174. global _default_root
  175. _default_root = None
  176. del _default_root
  177. def _tkerror(err):
  178. """Internal function."""
  179. pass
  180. def _exit(code=0):
  181. """Internal function. Calling it will raise the exception SystemExit."""
  182. try:
  183. code = int(code)
  184. except ValueError:
  185. pass
  186. raise SystemExit, code
  187. _varnum = 0
  188. class Variable:
  189. """Class to define value holders for e.g. buttons.
  190. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
  191. that constrain the type of the value returned from get()."""
  192. _default = ""
  193. _tclCommands = None
  194. def __init__(self, master=None, value=None, name=None):
  195. """Construct a variable
  196. MASTER can be given as master widget.
  197. VALUE is an optional value (defaults to "")
  198. NAME is an optional Tcl name (defaults to PY_VARnum).
  199. If NAME matches an existing variable and VALUE is omitted
  200. then the existing value is retained.
  201. """
  202. global _varnum
  203. if not master:
  204. master = _default_root
  205. self._root = master._root()
  206. self._tk = master.tk
  207. if name:
  208. self._name = name
  209. else:
  210. self._name = 'PY_VAR' + repr(_varnum)
  211. _varnum += 1
  212. if value is not None:
  213. self.set(value)
  214. elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)):
  215. self.set(self._default)
  216. def __del__(self):
  217. """Unset the variable in Tcl."""
  218. if self._tk is None:
  219. return
  220. if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
  221. self._tk.globalunsetvar(self._name)
  222. if self._tclCommands is not None:
  223. for name in self._tclCommands:
  224. #print '- Tkinter: deleted command', name
  225. self._tk.deletecommand(name)
  226. self._tclCommands = None
  227. def __str__(self):
  228. """Return the name of the variable in Tcl."""
  229. return self._name
  230. def set(self, value):
  231. """Set the variable to VALUE."""
  232. return self._tk.globalsetvar(self._name, value)
  233. def get(self):
  234. """Return value of variable."""
  235. return self._tk.globalgetvar(self._name)
  236. def trace_variable(self, mode, callback):
  237. """Define a trace callback for the variable.
  238. MODE is one of "r", "w", "u" for read, write, undefine.
  239. CALLBACK must be a function which is called when
  240. the variable is read, written or undefined.
  241. Return the name of the callback.
  242. """
  243. f = CallWrapper(callback, None, self._root).__call__
  244. cbname = repr(id(f))
  245. try:
  246. callback = callback.im_func
  247. except AttributeError:
  248. pass
  249. try:
  250. cbname = cbname + callback.__name__
  251. except AttributeError:
  252. pass
  253. self._tk.createcommand(cbname, f)
  254. if self._tclCommands is None:
  255. self._tclCommands = []
  256. self._tclCommands.append(cbname)
  257. self._tk.call("trace", "variable", self._name, mode, cbname)
  258. return cbname
  259. trace = trace_variable
  260. def trace_vdelete(self, mode, cbname):
  261. """Delete the trace callback for a variable.
  262. MODE is one of "r", "w", "u" for read, write, undefine.
  263. CBNAME is the name of the callback returned from trace_variable or trace.
  264. """
  265. self._tk.call("trace", "vdelete", self._name, mode, cbname)
  266. self._tk.deletecommand(cbname)
  267. try:
  268. self._tclCommands.remove(cbname)
  269. except ValueError:
  270. pass
  271. def trace_vinfo(self):
  272. """Return all trace callback information."""
  273. return map(self._tk.split, self._tk.splitlist(
  274. self._tk.call("trace", "vinfo", self._name)))
  275. def __eq__(self, other):
  276. """Comparison for equality (==).
  277. Note: if the Variable's master matters to behavior
  278. also compare self._master == other._master
  279. """
  280. return self.__class__.__name__ == other.__class__.__name__ \
  281. and self._name == other._name
  282. class StringVar(Variable):
  283. """Value holder for strings variables."""
  284. _default = ""
  285. def __init__(self, master=None, value=None, name=None):
  286. """Construct a string variable.
  287. MASTER can be given as master widget.
  288. VALUE is an optional value (defaults to "")
  289. NAME is an optional Tcl name (defaults to PY_VARnum).
  290. If NAME matches an existing variable and VALUE is omitted
  291. then the existing value is retained.
  292. """
  293. Variable.__init__(self, master, value, name)
  294. def get(self):
  295. """Return value of variable as string."""
  296. value = self._tk.globalgetvar(self._name)
  297. if isinstance(value, basestring):
  298. return value
  299. return str(value)
  300. class IntVar(Variable):
  301. """Value holder for integer variables."""
  302. _default = 0
  303. def __init__(self, master=None, value=None, name=None):
  304. """Construct an integer variable.
  305. MASTER can be given as master widget.
  306. VALUE is an optional value (defaults to 0)
  307. NAME is an optional Tcl name (defaults to PY_VARnum).
  308. If NAME matches an existing variable and VALUE is omitted
  309. then the existing value is retained.
  310. """
  311. Variable.__init__(self, master, value, name)
  312. def set(self, value):
  313. """Set the variable to value, converting booleans to integers."""
  314. if isinstance(value, bool):
  315. value = int(value)
  316. return Variable.set(self, value)
  317. def get(self):
  318. """Return the value of the variable as an integer."""
  319. return getint(self._tk.globalgetvar(self._name))
  320. class DoubleVar(Variable):
  321. """Value holder for float variables."""
  322. _default = 0.0
  323. def __init__(self, master=None, value=None, name=None):
  324. """Construct a float variable.
  325. MASTER can be given as master widget.
  326. VALUE is an optional value (defaults to 0.0)
  327. NAME is an optional Tcl name (defaults to PY_VARnum).
  328. If NAME matches an existing variable and VALUE is omitted
  329. then the existing value is retained.
  330. """
  331. Variable.__init__(self, master, value, name)
  332. def get(self):
  333. """Return the value of the variable as a float."""
  334. return getdouble(self._tk.globalgetvar(self._name))
  335. class BooleanVar(Variable):
  336. """Value holder for boolean variables."""
  337. _default = False
  338. def __init__(self, master=None, value=None, name=None):
  339. """Construct a boolean variable.
  340. MASTER can be given as master widget.
  341. VALUE is an optional value (defaults to False)
  342. NAME is an optional Tcl name (defaults to PY_VARnum).
  343. If NAME matches an existing variable and VALUE is omitted
  344. then the existing value is retained.
  345. """
  346. Variable.__init__(self, master, value, name)
  347. def set(self, value):
  348. """Set the variable to VALUE."""
  349. return self._tk.globalsetvar(self._name, self._tk.getboolean(value))
  350. def get(self):
  351. """Return the value of the variable as a bool."""
  352. return self._tk.getboolean(self._tk.globalgetvar(self._name))
  353. def mainloop(n=0):
  354. """Run the main loop of Tcl."""
  355. _default_root.tk.mainloop(n)
  356. getint = int
  357. getdouble = float
  358. def getboolean(s):
  359. """Convert true and false to integer values 1 and 0."""
  360. return _default_root.tk.getboolean(s)
  361. # Methods defined on both toplevel and interior widgets
  362. class Misc:
  363. """Internal class.
  364. Base class which defines methods common for interior widgets."""
  365. # XXX font command?
  366. _tclCommands = None
  367. def destroy(self):
  368. """Internal function.
  369. Delete all Tcl commands created for
  370. this widget in the Tcl interpreter."""
  371. if self._tclCommands is not None:
  372. for name in self._tclCommands:
  373. #print '- Tkinter: deleted command', name
  374. self.tk.deletecommand(name)
  375. self._tclCommands = None
  376. def deletecommand(self, name):
  377. """Internal function.
  378. Delete the Tcl command provided in NAME."""
  379. #print '- Tkinter: deleted command', name
  380. self.tk.deletecommand(name)
  381. try:
  382. self._tclCommands.remove(name)
  383. except ValueError:
  384. pass
  385. def tk_strictMotif(self, boolean=None):
  386. """Set Tcl internal variable, whether the look and feel
  387. should adhere to Motif.
  388. A parameter of 1 means adhere to Motif (e.g. no color
  389. change if mouse passes over slider).
  390. Returns the set value."""
  391. return self.tk.getboolean(self.tk.call(
  392. 'set', 'tk_strictMotif', boolean))
  393. def tk_bisque(self):
  394. """Change the color scheme to light brown as used in Tk 3.6 and before."""
  395. self.tk.call('tk_bisque')
  396. def tk_setPalette(self, *args, **kw):
  397. """Set a new color scheme for all widget elements.
  398. A single color as argument will cause that all colors of Tk
  399. widget elements are derived from this.
  400. Alternatively several keyword parameters and its associated
  401. colors can be given. The following keywords are valid:
  402. activeBackground, foreground, selectColor,
  403. activeForeground, highlightBackground, selectBackground,
  404. background, highlightColor, selectForeground,
  405. disabledForeground, insertBackground, troughColor."""
  406. self.tk.call(('tk_setPalette',)
  407. + _flatten(args) + _flatten(kw.items()))
  408. def tk_menuBar(self, *args):
  409. """Do not use. Needed in Tk 3.6 and earlier."""
  410. # obsolete since Tk 4.0
  411. import warnings
  412. warnings.warn('tk_menuBar() does nothing and will be removed in 3.6',
  413. DeprecationWarning, stacklevel=2)
  414. def wait_variable(self, name='PY_VAR'):
  415. """Wait until the variable is modified.
  416. A parameter of type IntVar, StringVar, DoubleVar or
  417. BooleanVar must be given."""
  418. self.tk.call('tkwait', 'variable', name)
  419. waitvar = wait_variable # XXX b/w compat
  420. def wait_window(self, window=None):
  421. """Wait until a WIDGET is destroyed.
  422. If no parameter is given self is used."""
  423. if window is None:
  424. window = self
  425. self.tk.call('tkwait', 'window', window._w)
  426. def wait_visibility(self, window=None):
  427. """Wait until the visibility of a WIDGET changes
  428. (e.g. it appears).
  429. If no parameter is given self is used."""
  430. if window is None:
  431. window = self
  432. self.tk.call('tkwait', 'visibility', window._w)
  433. def setvar(self, name='PY_VAR', value='1'):
  434. """Set Tcl variable NAME to VALUE."""
  435. self.tk.setvar(name, value)
  436. def getvar(self, name='PY_VAR'):
  437. """Return value of Tcl variable NAME."""
  438. return self.tk.getvar(name)
  439. getint = int
  440. getdouble = float
  441. def getboolean(self, s):
  442. """Return a boolean value for Tcl boolean values true and false given as parameter."""
  443. return self.tk.getboolean(s)
  444. def focus_set(self):
  445. """Direct input focus to this widget.
  446. If the application currently does not have the focus
  447. this widget will get the focus if the application gets
  448. the focus through the window manager."""
  449. self.tk.call('focus', self._w)
  450. focus = focus_set # XXX b/w compat?
  451. def focus_force(self):
  452. """Direct input focus to this widget even if the
  453. application does not have the focus. Use with
  454. caution!"""
  455. self.tk.call('focus', '-force', self._w)
  456. def focus_get(self):
  457. """Return the widget which has currently the focus in the
  458. application.
  459. Use focus_displayof to allow working with several
  460. displays. Return None if application does not have
  461. the focus."""
  462. name = self.tk.call('focus')
  463. if name == 'none' or not name: return None
  464. return self._nametowidget(name)
  465. def focus_displayof(self):
  466. """Return the widget which has currently the focus on the
  467. display where this widget is located.
  468. Return None if the application does not have the focus."""
  469. name = self.tk.call('focus', '-displayof', self._w)
  470. if name == 'none' or not name: return None
  471. return self._nametowidget(name)
  472. def focus_lastfor(self):
  473. """Return the widget which would have the focus if top level
  474. for this widget gets the focus from the window manager."""
  475. name = self.tk.call('focus', '-lastfor', self._w)
  476. if name == 'none' or not name: return None
  477. return self._nametowidget(name)
  478. def tk_focusFollowsMouse(self):
  479. """The widget under mouse will get automatically focus. Can not
  480. be disabled easily."""
  481. self.tk.call('tk_focusFollowsMouse')
  482. def tk_focusNext(self):
  483. """Return the next widget in the focus order which follows
  484. widget which has currently the focus.
  485. The focus order first goes to the next child, then to
  486. the children of the child recursively and then to the
  487. next sibling which is higher in the stacking order. A
  488. widget is omitted if it has the takefocus resource set
  489. to 0."""
  490. name = self.tk.call('tk_focusNext', self._w)
  491. if not name: return None
  492. return self._nametowidget(name)
  493. def tk_focusPrev(self):
  494. """Return previous widget in the focus order. See tk_focusNext for details."""
  495. name = self.tk.call('tk_focusPrev', self._w)
  496. if not name: return None
  497. return self._nametowidget(name)
  498. def after(self, ms, func=None, *args):
  499. """Call function once after given time.
  500. MS specifies the time in milliseconds. FUNC gives the
  501. function which shall be called. Additional parameters
  502. are given as parameters to the function call. Return
  503. identifier to cancel scheduling with after_cancel."""
  504. if not func:
  505. # I'd rather use time.sleep(ms*0.001)
  506. self.tk.call('after', ms)
  507. else:
  508. def callit():
  509. try:
  510. func(*args)
  511. finally:
  512. try:
  513. self.deletecommand(name)
  514. except TclError:
  515. pass
  516. callit.__name__ = func.__name__
  517. name = self._register(callit)
  518. return self.tk.call('after', ms, name)
  519. def after_idle(self, func, *args):
  520. """Call FUNC once if the Tcl main loop has no event to
  521. process.
  522. Return an identifier to cancel the scheduling with
  523. after_cancel."""
  524. return self.after('idle', func, *args)
  525. def after_cancel(self, id):
  526. """Cancel scheduling of function identified with ID.
  527. Identifier returned by after or after_idle must be
  528. given as first parameter."""
  529. try:
  530. data = self.tk.call('after', 'info', id)
  531. # In Tk 8.3, splitlist returns: (script, type)
  532. # In Tk 8.4, splitlist may return (script, type) or (script,)
  533. script = self.tk.splitlist(data)[0]
  534. self.deletecommand(script)
  535. except TclError:
  536. pass
  537. self.tk.call('after', 'cancel', id)
  538. def bell(self, displayof=0):
  539. """Ring a display's bell."""
  540. self.tk.call(('bell',) + self._displayof(displayof))
  541. # Clipboard handling:
  542. def clipboard_get(self, **kw):
  543. """Retrieve data from the clipboard on window's display.
  544. The window keyword defaults to the root window of the Tkinter
  545. application.
  546. The type keyword specifies the form in which the data is
  547. to be returned and should be an atom name such as STRING
  548. or FILE_NAME. Type defaults to STRING, except on X11, where the default
  549. is to try UTF8_STRING and fall back to STRING.
  550. This command is equivalent to:
  551. selection_get(CLIPBOARD)
  552. """
  553. if 'type' not in kw and self._windowingsystem == 'x11':
  554. try:
  555. kw['type'] = 'UTF8_STRING'
  556. return self.tk.call(('clipboard', 'get') + self._options(kw))
  557. except TclError:
  558. del kw['type']
  559. return self.tk.call(('clipboard', 'get') + self._options(kw))
  560. def clipboard_clear(self, **kw):
  561. """Clear the data in the Tk clipboard.
  562. A widget specified for the optional displayof keyword
  563. argument specifies the target display."""
  564. if 'displayof' not in kw: kw['displayof'] = self._w
  565. self.tk.call(('clipboard', 'clear') + self._options(kw))
  566. def clipboard_append(self, string, **kw):
  567. """Append STRING to the Tk clipboard.
  568. A widget specified at the optional displayof keyword
  569. argument specifies the target display. The clipboard
  570. can be retrieved with selection_get."""
  571. if 'displayof' not in kw: kw['displayof'] = self._w
  572. self.tk.call(('clipboard', 'append') + self._options(kw)
  573. + ('--', string))
  574. # XXX grab current w/o window argument
  575. def grab_current(self):
  576. """Return widget which has currently the grab in this application
  577. or None."""
  578. name = self.tk.call('grab', 'current', self._w)
  579. if not name: return None
  580. return self._nametowidget(name)
  581. def grab_release(self):
  582. """Release grab for this widget if currently set."""
  583. self.tk.call('grab', 'release', self._w)
  584. def grab_set(self):
  585. """Set grab for this widget.
  586. A grab directs all events to this and descendant
  587. widgets in the application."""
  588. self.tk.call('grab', 'set', self._w)
  589. def grab_set_global(self):
  590. """Set global grab for this widget.
  591. A global grab directs all events to this and
  592. descendant widgets on the display. Use with caution -
  593. other applications do not get events anymore."""
  594. self.tk.call('grab', 'set', '-global', self._w)
  595. def grab_status(self):
  596. """Return None, "local" or "global" if this widget has
  597. no, a local or a global grab."""
  598. status = self.tk.call('grab', 'status', self._w)
  599. if status == 'none': status = None
  600. return status
  601. def option_add(self, pattern, value, priority = None):
  602. """Set a VALUE (second parameter) for an option
  603. PATTERN (first parameter).
  604. An optional third parameter gives the numeric priority
  605. (defaults to 80)."""
  606. self.tk.call('option', 'add', pattern, value, priority)
  607. def option_clear(self):
  608. """Clear the option database.
  609. It will be reloaded if option_add is called."""
  610. self.tk.call('option', 'clear')
  611. def option_get(self, name, className):
  612. """Return the value for an option NAME for this widget
  613. with CLASSNAME.
  614. Values with higher priority override lower values."""
  615. return self.tk.call('option', 'get', self._w, name, className)
  616. def option_readfile(self, fileName, priority = None):
  617. """Read file FILENAME into the option database.
  618. An optional second parameter gives the numeric
  619. priority."""
  620. self.tk.call('option', 'readfile', fileName, priority)
  621. def selection_clear(self, **kw):
  622. """Clear the current X selection."""
  623. if 'displayof' not in kw: kw['displayof'] = self._w
  624. self.tk.call(('selection', 'clear') + self._options(kw))
  625. def selection_get(self, **kw):
  626. """Return the contents of the current X selection.
  627. A keyword parameter selection specifies the name of
  628. the selection and defaults to PRIMARY. A keyword
  629. parameter displayof specifies a widget on the display
  630. to use. A keyword parameter type specifies the form of data to be
  631. fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
  632. before STRING."""
  633. if 'displayof' not in kw: kw['displayof'] = self._w
  634. if 'type' not in kw and self._windowingsystem == 'x11':
  635. try:
  636. kw['type'] = 'UTF8_STRING'
  637. return self.tk.call(('selection', 'get') + self._options(kw))
  638. except TclError:
  639. del kw['type']
  640. return self.tk.call(('selection', 'get') + self._options(kw))
  641. def selection_handle(self, command, **kw):
  642. """Specify a function COMMAND to call if the X
  643. selection owned by this widget is queried by another
  644. application.
  645. This function must return the contents of the
  646. selection. The function will be called with the
  647. arguments OFFSET and LENGTH which allows the chunking
  648. of very long selections. The following keyword
  649. parameters can be provided:
  650. selection - name of the selection (default PRIMARY),
  651. type - type of the selection (e.g. STRING, FILE_NAME)."""
  652. name = self._register(command)
  653. self.tk.call(('selection', 'handle') + self._options(kw)
  654. + (self._w, name))
  655. def selection_own(self, **kw):
  656. """Become owner of X selection.
  657. A keyword parameter selection specifies the name of
  658. the selection (default PRIMARY)."""
  659. self.tk.call(('selection', 'own') +
  660. self._options(kw) + (self._w,))
  661. def selection_own_get(self, **kw):
  662. """Return owner of X selection.
  663. The following keyword parameter can
  664. be provided:
  665. selection - name of the selection (default PRIMARY),
  666. type - type of the selection (e.g. STRING, FILE_NAME)."""
  667. if 'displayof' not in kw: kw['displayof'] = self._w
  668. name = self.tk.call(('selection', 'own') + self._options(kw))
  669. if not name: return None
  670. return self._nametowidget(name)
  671. def send(self, interp, cmd, *args):
  672. """Send Tcl command CMD to different interpreter INTERP to be executed."""
  673. return self.tk.call(('send', interp, cmd) + args)
  674. def lower(self, belowThis=None):
  675. """Lower this widget in the stacking order."""
  676. self.tk.call('lower', self._w, belowThis)
  677. def tkraise(self, aboveThis=None):
  678. """Raise this widget in the stacking order."""
  679. self.tk.call('raise', self._w, aboveThis)
  680. lift = tkraise
  681. def colormodel(self, value=None):
  682. """Useless. Not implemented in Tk."""
  683. return self.tk.call('tk', 'colormodel', self._w, value)
  684. def winfo_atom(self, name, displayof=0):
  685. """Return integer which represents atom NAME."""
  686. args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
  687. return getint(self.tk.call(args))
  688. def winfo_atomname(self, id, displayof=0):
  689. """Return name of atom with identifier ID."""
  690. args = ('winfo', 'atomname') \
  691. + self._displayof(displayof) + (id,)
  692. return self.tk.call(args)
  693. def winfo_cells(self):
  694. """Return number of cells in the colormap for this widget."""
  695. return getint(
  696. self.tk.call('winfo', 'cells', self._w))
  697. def winfo_children(self):
  698. """Return a list of all widgets which are children of this widget."""
  699. result = []
  700. for child in self.tk.splitlist(
  701. self.tk.call('winfo', 'children', self._w)):
  702. try:
  703. # Tcl sometimes returns extra windows, e.g. for
  704. # menus; those need to be skipped
  705. result.append(self._nametowidget(child))
  706. except KeyError:
  707. pass
  708. return result
  709. def winfo_class(self):
  710. """Return window class name of this widget."""
  711. return self.tk.call('winfo', 'class', self._w)
  712. def winfo_colormapfull(self):
  713. """Return true if at the last color request the colormap was full."""
  714. return self.tk.getboolean(
  715. self.tk.call('winfo', 'colormapfull', self._w))
  716. def winfo_containing(self, rootX, rootY, displayof=0):
  717. """Return the widget which is at the root coordinates ROOTX, ROOTY."""
  718. args = ('winfo', 'containing') \
  719. + self._displayof(displayof) + (rootX, rootY)
  720. name = self.tk.call(args)
  721. if not name: return None
  722. return self._nametowidget(name)
  723. def winfo_depth(self):
  724. """Return the number of bits per pixel."""
  725. return getint(self.tk.call('winfo', 'depth', self._w))
  726. def winfo_exists(self):
  727. """Return true if this widget exists."""
  728. return getint(
  729. self.tk.call('winfo', 'exists', self._w))
  730. def winfo_fpixels(self, number):
  731. """Return the number of pixels for the given distance NUMBER
  732. (e.g. "3c") as float."""
  733. return getdouble(self.tk.call(
  734. 'winfo', 'fpixels', self._w, number))
  735. def winfo_geometry(self):
  736. """Return geometry string for this widget in the form "widthxheight+X+Y"."""
  737. return self.tk.call('winfo', 'geometry', self._w)
  738. def winfo_height(self):
  739. """Return height of this widget."""
  740. return getint(
  741. self.tk.call('winfo', 'height', self._w))
  742. def winfo_id(self):
  743. """Return identifier ID for this widget."""
  744. return self.tk.getint(
  745. self.tk.call('winfo', 'id', self._w))
  746. def winfo_interps(self, displayof=0):
  747. """Return the name of all Tcl interpreters for this display."""
  748. args = ('winfo', 'interps') + self._displayof(displayof)
  749. return self.tk.splitlist(self.tk.call(args))
  750. def winfo_ismapped(self):
  751. """Return true if this widget is mapped."""
  752. return getint(
  753. self.tk.call('winfo', 'ismapped', self._w))
  754. def winfo_manager(self):
  755. """Return the window mananger name for this widget."""
  756. return self.tk.call('winfo', 'manager', self._w)
  757. def winfo_name(self):
  758. """Return the name of this widget."""
  759. return self.tk.call('winfo', 'name', self._w)
  760. def winfo_parent(self):
  761. """Return the name of the parent of this widget."""
  762. return self.tk.call('winfo', 'parent', self._w)
  763. def winfo_pathname(self, id, displayof=0):
  764. """Return the pathname of the widget given by ID."""
  765. args = ('winfo', 'pathname') \
  766. + self._displayof(displayof) + (id,)
  767. return self.tk.call(args)
  768. def winfo_pixels(self, number):
  769. """Rounded integer value of winfo_fpixels."""
  770. return getint(
  771. self.tk.call('winfo', 'pixels', self._w, number))
  772. def winfo_pointerx(self):
  773. """Return the x coordinate of the pointer on the root window."""
  774. return getint(
  775. self.tk.call('winfo', 'pointerx', self._w))
  776. def winfo_pointerxy(self):
  777. """Return a tuple of x and y coordinates of the pointer on the root window."""
  778. return self._getints(
  779. self.tk.call('winfo', 'pointerxy', self._w))
  780. def winfo_pointery(self):
  781. """Return the y coordinate of the pointer on the root window."""
  782. return getint(
  783. self.tk.call('winfo', 'pointery', self._w))
  784. def winfo_reqheight(self):
  785. """Return requested height of this widget."""
  786. return getint(
  787. self.tk.call('winfo', 'reqheight', self._w))
  788. def winfo_reqwidth(self):
  789. """Return requested width of this widget."""
  790. return getint(
  791. self.tk.call('winfo', 'reqwidth', self._w))
  792. def winfo_rgb(self, color):
  793. """Return tuple of decimal values for red, green, blue for
  794. COLOR in this widget."""
  795. return self._getints(
  796. self.tk.call('winfo', 'rgb', self._w, color))
  797. def winfo_rootx(self):
  798. """Return x coordinate of upper left corner of this widget on the
  799. root window."""
  800. return getint(
  801. self.tk.call('winfo', 'rootx', self._w))
  802. def winfo_rooty(self):
  803. """Return y coordinate of upper left corner of this widget on the
  804. root window."""
  805. return getint(
  806. self.tk.call('winfo', 'rooty', self._w))
  807. def winfo_screen(self):
  808. """Return the screen name of this widget."""
  809. return self.tk.call('winfo', 'screen', self._w)
  810. def winfo_screencells(self):
  811. """Return the number of the cells in the colormap of the screen
  812. of this widget."""
  813. return getint(
  814. self.tk.call('winfo', 'screencells', self._w))
  815. def winfo_screendepth(self):
  816. """Return the number of bits per pixel of the root window of the
  817. screen of this widget."""
  818. return getint(
  819. self.tk.call('winfo', 'screendepth', self._w))
  820. def winfo_screenheight(self):
  821. """Return the number of pixels of the height of the screen of this widget
  822. in pixel."""
  823. return getint(
  824. self.tk.call('winfo', 'screenheight', self._w))
  825. def winfo_screenmmheight(self):
  826. """Return the number of pixels of the height of the screen of
  827. this widget in mm."""
  828. return getint(
  829. self.tk.call('winfo', 'screenmmheight', self._w))
  830. def winfo_screenmmwidth(self):
  831. """Return the number of pixels of the width of the screen of
  832. this widget in mm."""
  833. return getint(
  834. self.tk.call('winfo', 'screenmmwidth', self._w))
  835. def winfo_screenvisual(self):
  836. """Return one of the strings directcolor, grayscale, pseudocolor,
  837. staticcolor, staticgray, or truecolor for the default
  838. colormodel of this screen."""
  839. return self.tk.call('winfo', 'screenvisual', self._w)
  840. def winfo_screenwidth(self):
  841. """Return the number of pixels of the width of the screen of
  842. this widget in pixel."""
  843. return getint(
  844. self.tk.call('winfo', 'screenwidth', self._w))
  845. def winfo_server(self):
  846. """Return information of the X-Server of the screen of this widget in
  847. the form "XmajorRminor vendor vendorVersion"."""
  848. return self.tk.call('winfo', 'server', self._w)
  849. def winfo_toplevel(self):
  850. """Return the toplevel widget of this widget."""
  851. return self._nametowidget(self.tk.call(
  852. 'winfo', 'toplevel', self._w))
  853. def winfo_viewable(self):
  854. """Return true if the widget and all its higher ancestors are mapped."""
  855. return getint(
  856. self.tk.call('winfo', 'viewable', self._w))
  857. def winfo_visual(self):
  858. """Return one of the strings directcolor, grayscale, pseudocolor,
  859. staticcolor, staticgray, or truecolor for the
  860. colormodel of this widget."""
  861. return self.tk.call('winfo', 'visual', self._w)
  862. def winfo_visualid(self):
  863. """Return the X identifier for the visual for this widget."""
  864. return self.tk.call('winfo', 'visualid', self._w)
  865. def winfo_visualsavailable(self, includeids=0):
  866. """Return a list of all visuals available for the screen
  867. of this widget.
  868. Each item in the list consists of a visual name (see winfo_visual), a
  869. depth and if INCLUDEIDS=1 is given also the X identifier."""
  870. data = self.tk.split(
  871. self.tk.call('winfo', 'visualsavailable', self._w,
  872. includeids and 'includeids' or None))
  873. if type(data) is StringType:
  874. data = [self.tk.split(data)]
  875. return map(self.__winfo_parseitem, data)
  876. def __winfo_parseitem(self, t):
  877. """Internal function."""
  878. return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
  879. def __winfo_getint(self, x):
  880. """Internal function."""
  881. return int(x, 0)
  882. def winfo_vrootheight(self):
  883. """Return the height of the virtual root window associated with this
  884. widget in pixels. If there is no virtual root window return the
  885. height of the screen."""
  886. return getint(
  887. self.tk.call('winfo', 'vrootheight', self._w))
  888. def winfo_vrootwidth(self):
  889. """Return the width of the virtual root window associated with this
  890. widget in pixel. If there is no virtual root window return the
  891. width of the screen."""
  892. return getint(
  893. self.tk.call('winfo', 'vrootwidth', self._w))
  894. def winfo_vrootx(self):
  895. """Return the x offset of the virtual root relative to the root
  896. window of the screen of this widget."""
  897. return getint(
  898. self.tk.call('winfo', 'vrootx', self._w))
  899. def winfo_vrooty(self):
  900. """Return the y offset of the virtual root relative to the root
  901. window of the screen of this widget."""
  902. return getint(
  903. self.tk.call('winfo', 'vrooty', self._w))
  904. def winfo_width(self):
  905. """Return the width of this widget."""
  906. return getint(
  907. self.tk.call('winfo', 'width', self._w))
  908. def winfo_x(self):
  909. """Return the x coordinate of the upper left corner of this widget
  910. in the parent."""
  911. return getint(
  912. self.tk.call('winfo', 'x', self._w))
  913. def winfo_y(self):
  914. """Return the y coordinate of the upper left corner of this widget
  915. in the parent."""
  916. return getint(
  917. self.tk.call('winfo', 'y', self._w))
  918. def update(self):
  919. """Enter event loop until all pending events have been processed by Tcl."""
  920. self.tk.call('update')
  921. def update_idletasks(self):
  922. """Enter event loop until all idle callbacks have been called. This
  923. will update the display of windows but not process events caused by
  924. the user."""
  925. self.tk.call('update', 'idletasks')
  926. def bindtags(self, tagList=None):
  927. """Set or get the list of bindtags for this widget.
  928. With no argument return the list of all bindtags associated with
  929. this widget. With a list of strings as argument the bindtags are
  930. set to this list. The bindtags determine in which order events are
  931. processed (see bind)."""
  932. if tagList is None:
  933. return self.tk.splitlist(
  934. self.tk.call('bindtags', self._w))
  935. else:
  936. self.tk.call('bindtags', self._w, tagList)
  937. def _bind(self, what, sequence, func, add, needcleanup=1):
  938. """Internal function."""
  939. if type(func) is StringType:
  940. self.tk.call(what + (sequence, func))
  941. elif func:
  942. funcid = self._register(func, self._substitute,
  943. needcleanup)
  944. cmd = ('%sif {"[%s %s]" == "break"} break\n'
  945. %
  946. (add and '+' or '',
  947. funcid, self._subst_format_str))
  948. self.tk.call(what + (sequence, cmd))
  949. return funcid
  950. elif sequence:
  951. return self.tk.call(what + (sequence,))
  952. else:
  953. return self.tk.splitlist(self.tk.call(what))
  954. def bind(self, sequence=None, func=None, add=None):
  955. """Bind to this widget at event SEQUENCE a call to function FUNC.
  956. SEQUENCE is a string of concatenated event
  957. patterns. An event pattern is of the form
  958. <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
  959. of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
  960. Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
  961. B3, Alt, Button4, B4, Double, Button5, B5 Triple,
  962. Mod1, M1. TYPE is one of Activate, Enter, Map,
  963. ButtonPress, Button, Expose, Motion, ButtonRelease
  964. FocusIn, MouseWheel, Circulate, FocusOut, Property,
  965. Colormap, Gravity Reparent, Configure, KeyPress, Key,
  966. Unmap, Deactivate, KeyRelease Visibility, Destroy,
  967. Leave and DETAIL is the button number for ButtonPress,
  968. ButtonRelease and DETAIL is the Keysym for KeyPress and
  969. KeyRelease. Examples are
  970. <Control-Button-1> for pressing Control and mouse button 1 or
  971. <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
  972. An event pattern can also be a virtual event of the form
  973. <<AString>> where AString can be arbitrary. This
  974. event can be generated by event_generate.
  975. If events are concatenated they must appear shortly
  976. after each other.
  977. FUNC will be called if the event sequence occurs with an
  978. instance of Event as argument. If the return value of FUNC is
  979. "break" no further bound function is invoked.
  980. An additional boolean parameter ADD specifies whether FUNC will
  981. be called additionally to the other bound function or whether
  982. it will replace the previous function.
  983. Bind will return an identifier to allow deletion of the bound function with
  984. unbind without memory leak.
  985. If FUNC or SEQUENCE is omitted the bound function or list
  986. of bound events are returned."""
  987. return self._bind(('bind', self._w), sequence, func, add)
  988. def unbind(self, sequence, funcid=None):
  989. """Unbind for this widget for event SEQUENCE the
  990. function identified with FUNCID."""
  991. self.tk.call('bind', self._w, sequence, '')
  992. if funcid:
  993. self.deletecommand(funcid)
  994. def bind_all(self, sequence=None, func=None, add=None):
  995. """Bind to all widgets at an event SEQUENCE a call to function FUNC.
  996. An additional boolean parameter ADD specifies whether FUNC will
  997. be called additionally to the other bound function or whether
  998. it will replace the previous function. See bind for the return value."""
  999. return self._bind(('bind', 'all'), sequence, func, add, 0)
  1000. def unbind_all(self, sequence):
  1001. """Unbind for all widgets for event SEQUENCE all functions."""
  1002. self.tk.call('bind', 'all' , sequence, '')
  1003. def bind_class(self, className, sequence=None, func=None, add=None):
  1004. """Bind to widgets with bindtag CLASSNAME at event
  1005. SEQUENCE a call of function FUNC. An additional
  1006. boolean parameter ADD specifies whether FUNC will be
  1007. called additionally to the other bound function or
  1008. whether it will replace the previous function. See bind for
  1009. the return value."""
  1010. return self._bind(('bind', className), sequence, func, add, 0)
  1011. def unbind_class(self, className, sequence):
  1012. """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
  1013. all functions."""
  1014. self.tk.call('bind', className , sequence, '')
  1015. def mainloop(self, n=0):
  1016. """Call the mainloop of Tk."""
  1017. self.tk.mainloop(n)
  1018. def quit(self):
  1019. """Quit the Tcl interpreter. All widgets will be destroyed."""
  1020. self.tk.quit()
  1021. def _getints(self, string):
  1022. """Internal function."""
  1023. if string:
  1024. return tuple(map(getint, self.tk.splitlist(string)))
  1025. def _getdoubles(self, string):
  1026. """Internal function."""
  1027. if string:
  1028. return tuple(map(getdouble, self.tk.splitlist(string)))
  1029. def _getboolean(self, string):
  1030. """Internal function."""
  1031. if string:
  1032. return self.tk.getboolean(string)
  1033. def _displayof(self, displayof):
  1034. """Internal function."""
  1035. if displayof:
  1036. return ('-displayof', displayof)
  1037. if displayof is None:
  1038. return ('-displayof', self._w)
  1039. return ()
  1040. @property
  1041. def _windowingsystem(self):
  1042. """Internal function."""
  1043. try:
  1044. return self._root()._windowingsystem_cached
  1045. except AttributeError:
  1046. ws = self._root()._windowingsystem_cached = \
  1047. self.tk.call('tk', 'windowingsystem')
  1048. return ws
  1049. def _options(self, cnf, kw = None):
  1050. """Internal function."""
  1051. if kw:
  1052. cnf = _cnfmerge((cnf, kw))
  1053. else:
  1054. cnf = _cnfmerge(cnf)
  1055. res = ()
  1056. for k, v in cnf.items():
  1057. if v is not None:
  1058. if k[-1] == '_': k = k[:-1]
  1059. if hasattr(v, '__call__'):
  1060. v = self._register(v)
  1061. elif isinstance(v, (tuple, list)):
  1062. nv = []
  1063. for item in v:
  1064. if not isinstance(item, (basestring, int)):
  1065. break
  1066. elif isinstance(item, int):
  1067. nv.append('%d' % item)
  1068. else:
  1069. # format it to proper Tcl code if it contains space
  1070. nv.append(_stringify(item))
  1071. else:
  1072. v = ' '.join(nv)
  1073. res = res + ('-'+k, v)
  1074. return res
  1075. def nametowidget(self, name):
  1076. """Return the Tkinter instance of a widget identified by
  1077. its Tcl name NAME."""
  1078. name = str(name).split('.')
  1079. w = self
  1080. if not name[0]:
  1081. w = w._root()
  1082. name = name[1:]
  1083. for n in name:
  1084. if not n:
  1085. break
  1086. w = w.children[n]
  1087. return w
  1088. _nametowidget = nametowidget
  1089. def _register(self, func, subst=None, needcleanup=1):
  1090. """Return a newly created Tcl function. If this
  1091. function is called, the Python function FUNC will
  1092. be executed. An optional function SUBST can
  1093. be given which will be executed before FUNC."""
  1094. f = CallWrapper(func, subst, self).__call__
  1095. name = repr(id(f))
  1096. try:
  1097. func = func.im_func
  1098. except AttributeError:
  1099. pass
  1100. try:
  1101. name = name + func.__name__
  1102. except AttributeError:
  1103. pass
  1104. self.tk.createcommand(name, f)
  1105. if needcleanup:
  1106. if self._tclCommands is None:
  1107. self._tclCommands = []
  1108. self._tclCommands.append(name)
  1109. return name
  1110. register = _register
  1111. def _root(self):
  1112. """Internal function."""
  1113. w = self
  1114. while w.master: w = w.master
  1115. return w
  1116. _subst_format = ('%#', '%b', '%f', '%h', '%k',
  1117. '%s', '%t', '%w', '%x', '%y',
  1118. '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
  1119. _subst_format_str = " ".join(_subst_format)
  1120. def _substitute(self, *args):
  1121. """Internal function."""
  1122. if len(args) != len(self._subst_format): return args
  1123. getboolean = self.tk.getboolean
  1124. getint = int
  1125. def getint_event(s):
  1126. """Tk changed behavior in 8.4.2, returning "??" rather more often."""
  1127. try:
  1128. return int(s)
  1129. except ValueError:
  1130. return s
  1131. nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
  1132. # Missing: (a, c, d, m, o, v, B, R)
  1133. e = Event()
  1134. # serial field: valid for all events
  1135. # number of button: ButtonPress and ButtonRelease events only
  1136. # height field: Configure, ConfigureRequest, Create,
  1137. # ResizeRequest, and Expose events only
  1138. # keycode field: KeyPress and KeyRelease events only
  1139. # time field: "valid for events that contain a time field"
  1140. # width field: Configure, ConfigureRequest, Create, ResizeRequest,
  1141. # and Expose events only
  1142. # x field: "valid for events that contain an x field"
  1143. # y field: "valid for events that contain a y field"
  1144. # keysym as decimal: KeyPress and KeyRelease events only
  1145. # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
  1146. # KeyRelease, and Motion events
  1147. e.serial = getint(nsign)
  1148. e.num = getint_event(b)
  1149. try: e.focus = getboolean(f)
  1150. except TclError: pass
  1151. e.height = getint_event(h)
  1152. e.keycode = getint_event(k)
  1153. e.state = getint_event(s)
  1154. e.time = getint_event(t)
  1155. e.width = getint_event(w)
  1156. e.x = getint_event(x)
  1157. e.y = getint_event(y)
  1158. e.char = A
  1159. try: e.send_event = getboolean(E)
  1160. except TclError: pass
  1161. e.keysym = K
  1162. e.keysym_num = getint_event(N)
  1163. e.type = T
  1164. try:
  1165. e.widget = self._nametowidget(W)
  1166. except KeyError:
  1167. e.widget = W
  1168. e.x_root = getint_event(X)
  1169. e.y_root = getint_event(Y)
  1170. try:
  1171. e.delta = getint(D)
  1172. except ValueError:
  1173. e.delta = 0
  1174. return (e,)
  1175. def _report_exception(self):
  1176. """Internal function."""
  1177. import sys
  1178. exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
  1179. root = self._root()
  1180. root.report_callback_exception(exc, val, tb)
  1181. def _getconfigure(self, *args):
  1182. """Call Tcl configure command and return the result as a dict."""
  1183. cnf = {}
  1184. for x in self.tk.splitlist(self.tk.call(*args)):
  1185. x = self.tk.splitlist(x)
  1186. cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1187. return cnf
  1188. def _getconfigure1(self, *args):
  1189. x = self.tk.splitlist(self.tk.call(*args))
  1190. return (x[0][1:],) + x[1:]
  1191. def _configure(self, cmd, cnf, kw):
  1192. """Internal function."""
  1193. if kw:
  1194. cnf = _cnfmerge((cnf, kw))
  1195. elif cnf:
  1196. cnf = _cnfmerge(cnf)
  1197. if cnf is None:
  1198. return self._getconfigure(_flatten((self._w, cmd)))
  1199. if type(cnf) is StringType:
  1200. return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
  1201. self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
  1202. # These used to be defined in Widget:
  1203. def configure(self, cnf=None, **kw):
  1204. """Configure resources of a widget.
  1205. The values for resources are specified as keyword
  1206. arguments. To get an overview about
  1207. the allowed keyword arguments call the method keys.
  1208. """
  1209. return self._configure('configure', cnf, kw)
  1210. config = configure
  1211. def cget(self, key):
  1212. """Return the resource value for a KEY given as string."""
  1213. return self.tk.call(self._w, 'cget', '-' + key)
  1214. __getitem__ = cget
  1215. def __setitem__(self, key, value):
  1216. self.configure({key: value})
  1217. def __contains__(self, key):
  1218. raise TypeError("Tkinter objects don't support 'in' tests.")
  1219. def keys(self):
  1220. """Return a list of all resource names of this widget."""
  1221. splitlist = self.tk.splitlist
  1222. return [splitlist(x)[0][1:] for x in
  1223. splitlist(self.tk.call(self._w, 'configure'))]
  1224. def __str__(self):
  1225. """Return the window path name of this widget."""
  1226. return self._w
  1227. # Pack methods that apply to the master
  1228. _noarg_ = ['_noarg_']
  1229. def pack_propagate(self, flag=_noarg_):
  1230. """Set or get the status for propagation of geometry information.
  1231. A boolean argument specifies whether the geometry information
  1232. of the slaves will determine the size of this widget. If no argument
  1233. is given the current setting will be returned.
  1234. """
  1235. if flag is Misc._noarg_:
  1236. return self._getboolean(self.tk.call(
  1237. 'pack', 'propagate', self._w))
  1238. else:
  1239. self.tk.call('pack', 'propagate', self._w, flag)
  1240. propagate = pack_propagate
  1241. def pack_slaves(self):
  1242. """Return a list of all slaves of this widget
  1243. in its packing order."""
  1244. return map(self._nametowidget,
  1245. self.tk.splitlist(
  1246. self.tk.call('pack', 'slaves', self._w)))
  1247. slaves = pack_slaves
  1248. # Place method that applies to the master
  1249. def place_slaves(self):
  1250. """Return a list of all slaves of this widget
  1251. in its packing order."""
  1252. return map(self._nametowidget,
  1253. self.tk.splitlist(
  1254. self.tk.call(
  1255. 'place', 'slaves', self._w)))
  1256. # Grid methods that apply to the master
  1257. def grid_bbox(self, column=None, row=None, col2=None, row2=None):
  1258. """Return a tuple of integer coordinates for the bounding
  1259. box of this widget controlled by the geometry manager grid.
  1260. If COLUMN, ROW is given the bounding box applies from
  1261. the cell with row and column 0 to the specified
  1262. cell. If COL2 and ROW2 are given the bounding box
  1263. starts at that cell.
  1264. The returned integers specify the offset of the upper left
  1265. corner in the master widget and the width and height.
  1266. """
  1267. args = ('grid', 'bbox', self._w)
  1268. if column is not None and row is not None:
  1269. args = args + (column, row)
  1270. if col2 is not None and row2 is not None:
  1271. args = args + (col2, row2)
  1272. return self._getints(self.tk.call(*args)) or None
  1273. bbox = grid_bbox
  1274. def _gridconvvalue(self, value):
  1275. if isinstance(value, (str, _tkinter.Tcl_Obj)):
  1276. try:
  1277. svalue = str(value)
  1278. if not svalue:
  1279. return None
  1280. elif '.' in svalue:
  1281. return getdouble(svalue)
  1282. else:
  1283. return getint(svalue)
  1284. except ValueError:
  1285. pass
  1286. return value
  1287. def _grid_configure(self, command, index, cnf, kw):
  1288. """Internal function."""
  1289. if type(cnf) is StringType and not kw:
  1290. if cnf[-1:] == '_':
  1291. cnf = cnf[:-1]
  1292. if cnf[:1] != '-':
  1293. cnf = '-'+cnf
  1294. options = (cnf,)
  1295. else:
  1296. options = self._options(cnf, kw)
  1297. if not options:
  1298. return _splitdict(
  1299. self.tk,
  1300. self.tk.call('grid', command, self._w, index),
  1301. conv=self._gridconvvalue)
  1302. res = self.tk.call(
  1303. ('grid', command, self._w, index)
  1304. + options)
  1305. if len(options) == 1:
  1306. return self._gridconvvalue(res)
  1307. def grid_columnconfigure(self, index, cnf={}, **kw):
  1308. """Configure column INDEX of a grid.
  1309. Valid resources are minsize (minimum size of the column),
  1310. weight (how much does additional space propagate to this column)
  1311. and pad (how much space to let additionally)."""
  1312. return self._grid_configure('columnconfigure', index, cnf, kw)
  1313. columnconfigure = grid_columnconfigure
  1314. def grid_location(self, x, y):
  1315. """Return a tuple of column and row which identify the cell
  1316. at which the pixel at position X and Y inside the master
  1317. widget is located."""
  1318. return self._getints(
  1319. self.tk.call(
  1320. 'grid', 'location', self._w, x, y)) or None
  1321. def grid_propagate(self, flag=_noarg_):
  1322. """Set or get the status for propagation of geometry information.
  1323. A boolean argument specifies whether the geometry information
  1324. of the slaves will determine the size of this widget. If no argument
  1325. is given, the current setting will be returned.
  1326. """
  1327. if flag is Misc._noarg_:
  1328. return self._getboolean(self.tk.call(
  1329. 'grid', 'propagate', self._w))
  1330. else:
  1331. self.tk.call('grid', 'propagate', self._w, flag)
  1332. def grid_rowconfigure(self, index, cnf={}, **kw):
  1333. """Configure row INDEX of a grid.
  1334. Valid resources are minsize (minimum size of the row),
  1335. weight (how much does additional space propagate to this row)
  1336. and pad (how much space to let additionally)."""
  1337. return self._grid_configure('rowconfigure', index, cnf, kw)
  1338. rowconfigure = grid_rowconfigure
  1339. def grid_size(self):
  1340. """Return a tuple of the number of column and rows in the grid."""
  1341. return self._getints(
  1342. self.tk.call('grid', 'size', self._w)) or None
  1343. size = grid_size
  1344. def grid_slaves(self, row=None, column=None):
  1345. """Return a list of all slaves of this widget
  1346. in its packing order."""
  1347. args = ()
  1348. if row is not None:
  1349. args = args + ('-row', row)
  1350. if column is not None:
  1351. args = args + ('-column', column)
  1352. return map(self._nametowidget,
  1353. self.tk.splitlist(self.tk.call(
  1354. ('grid', 'slaves', self._w) + args)))
  1355. # Support for the "event" command, new in Tk 4.2.
  1356. # By Case Roole.
  1357. def event_add(self, virtual, *sequences):
  1358. """Bind a virtual event VIRTUAL (of the form <<Name>>)
  1359. to an event SEQUENCE such that the virtual event is triggered
  1360. whenever SEQUENCE occurs."""
  1361. args = ('event', 'add', virtual) + sequences
  1362. self.tk.call(args)
  1363. def event_delete(self, virtual, *sequences):
  1364. """Unbind a virtual event VIRTUAL from SEQUENCE."""
  1365. args = ('event', 'delete', virtual) + sequences
  1366. self.tk.call(args)
  1367. def event_generate(self, sequence, **kw):
  1368. """Generate an event SEQUENCE. Additional
  1369. keyword arguments specify parameter of the event
  1370. (e.g. x, y, rootx, rooty)."""
  1371. args = ('event', 'generate', self._w, sequence)
  1372. for k, v in kw.items():
  1373. args = args + ('-%s' % k, str(v))
  1374. self.tk.call(args)
  1375. def event_info(self, virtual=None):
  1376. """Return a list of all virtual events or the information
  1377. about the SEQUENCE bound to the virtual event VIRTUAL."""
  1378. return self.tk.splitlist(
  1379. self.tk.call('event', 'info', virtual))
  1380. # Image related commands
  1381. def image_names(self):
  1382. """Return a list of all existing image names."""
  1383. return self.tk.splitlist(self.tk.call('image', 'names'))
  1384. def image_types(self):
  1385. """Return a list of all available image types (e.g. phote bitmap)."""
  1386. return self.tk.splitlist(self.tk.call('image', 'types'))
  1387. class CallWrapper:
  1388. """Internal class. Stores function to call when some user
  1389. defined Tcl function is called e.g. after an event occurred."""
  1390. def __init__(self, func, subst, widget):
  1391. """Store FUNC, SUBST and WIDGET as members."""
  1392. self.func = func
  1393. self.subst = subst
  1394. self.widget = widget
  1395. def __call__(self, *args):
  1396. """Apply first function SUBST to arguments, than FUNC."""
  1397. try:
  1398. if self.subst:
  1399. args = self.subst(*args)
  1400. return self.func(*args)
  1401. except SystemExit, msg:
  1402. raise SystemExit, msg
  1403. except:
  1404. self.widget._report_exception()
  1405. class XView:
  1406. """Mix-in class for querying and changing the horizontal position
  1407. of a widget's window."""
  1408. def xview(self, *args):
  1409. """Query and change the horizontal position of the view."""
  1410. res = self.tk.call(self._w, 'xview', *args)
  1411. if not args:
  1412. return self._getdoubles(res)
  1413. def xview_moveto(self, fraction):
  1414. """Adjusts the view in the window so that FRACTION of the
  1415. total width of the canvas is off-screen to the left."""
  1416. self.tk.call(self._w, 'xview', 'moveto', fraction)
  1417. def xview_scroll(self, number, what):
  1418. """Shift the x-view according to NUMBER which is measured in "units"
  1419. or "pages" (WHAT)."""
  1420. self.tk.call(self._w, 'xview', 'scroll', number, what)
  1421. class YView:
  1422. """Mix-in class for querying and changing the vertical position
  1423. of a widget's window."""
  1424. def yview(self, *args):
  1425. """Query and change the vertical position of the view."""
  1426. res = self.tk.call(self._w, 'yview', *args)
  1427. if not args:
  1428. return self._getdoubles(res)
  1429. def yview_moveto(self, fraction):
  1430. """Adjusts the view in the window so that FRACTION of the
  1431. total height of the canvas is off-screen to the top."""
  1432. self.tk.call(self._w, 'yview', 'moveto', fraction)
  1433. def yview_scroll(self, number, what):
  1434. """Shift the y-view according to NUMBER which is measured in
  1435. "units" or "pages" (WHAT)."""
  1436. self.tk.call(self._w, 'yview', 'scroll', number, what)
  1437. class Wm:
  1438. """Provides functions for the communication with the window manager."""
  1439. def wm_aspect(self,
  1440. minNumer=None, minDenom=None,
  1441. maxNumer=None, maxDenom=None):
  1442. """Instruct the window manager to set the aspect ratio (width/height)
  1443. of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
  1444. of the actual values if no argument is given."""
  1445. return self._getints(
  1446. self.tk.call('wm', 'aspect', self._w,
  1447. minNumer, minDenom,
  1448. maxNumer, maxDenom))
  1449. aspect = wm_aspect
  1450. def wm_attributes(self, *args):
  1451. """This subcommand returns or sets platform specific attributes
  1452. The first form returns a list of the platform specific flags and
  1453. their values. The second form returns the value for the specific
  1454. option. The third form sets one or more of the values. The values
  1455. are as follows:
  1456. On Windows, -disabled gets or sets whether the window is in a
  1457. disabled state. -toolwindow gets or sets the style of the window
  1458. to toolwindow (as defined in the MSDN). -topmost gets or sets
  1459. whether this is a topmost window (displays above all other
  1460. windows).
  1461. On Macintosh, XXXXX
  1462. On Unix, there are currently no special attribute values.
  1463. """
  1464. args = ('wm', 'attributes', self._w) + args
  1465. return self.tk.call(args)
  1466. attributes=wm_attributes
  1467. def wm_client(self, name=None):
  1468. """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
  1469. current value."""
  1470. return self.tk.call('wm', 'client', self._w, name)
  1471. client = wm_client
  1472. def wm_colormapwindows(self, *wlist):
  1473. """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
  1474. of this widget. This list contains windows whose colormaps differ from their
  1475. parents. Return current list of widgets if WLIST is empty."""
  1476. if len(wlist) > 1:
  1477. wlist = (wlist,) # Tk needs a list of windows here
  1478. args = ('wm', 'colormapwindows', self._w) + wlist
  1479. if wlist:
  1480. self.tk.call(args)
  1481. else:
  1482. return map(self._nametowidget, self.tk.splitlist(self.tk.call(args)))
  1483. colormapwindows = wm_colormapwindows
  1484. def wm_command(self, value=None):
  1485. """Store VALUE in WM_COMMAND property. It is the command
  1486. which shall be used to invoke the application. Return current
  1487. command if VALUE is None."""
  1488. return self.tk.call('wm', 'command', self._w, value)
  1489. command = wm_command
  1490. def wm_deiconify(self):
  1491. """Deiconify this widget. If it was never mapped it will not be mapped.
  1492. On Windows it will raise this widget and give it the focus."""
  1493. return self.tk.call('wm', 'deiconify', self._w)
  1494. deiconify = wm_deiconify
  1495. def wm_focusmodel(self, model=None):
  1496. """Set focus model to MODEL. "active" means that this widget will claim
  1497. the focus itself, "passive" means that the window manager shall give
  1498. the focus. Return current focus model if MODEL is None."""
  1499. return self.tk.call('wm', 'focusmodel', self._w, model)
  1500. focusmodel = wm_focusmodel
  1501. def wm_frame(self):
  1502. """Return identifier for decorative frame of this widget if present."""
  1503. return self.tk.call('wm', 'frame', self._w)
  1504. frame = wm_frame
  1505. def wm_geometry(self, newGeometry=None):
  1506. """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
  1507. current value if None is given."""
  1508. return self.tk.call('wm', 'geometry', self._w, newGeometry)
  1509. geometry = wm_geometry
  1510. def wm_grid(self,
  1511. baseWidth=None, baseHeight=None,
  1512. widthInc=None, heightInc=None):
  1513. """Instruct the window manager that this widget shall only be
  1514. resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
  1515. height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
  1516. number of grid units requested in Tk_GeometryRequest."""
  1517. return self._getints(self.tk.call(
  1518. 'wm', 'grid', self._w,
  1519. baseWidth, baseHeight, widthInc, heightInc))
  1520. grid = wm_grid
  1521. def wm_group(self, pathName=None):
  1522. """Set the group leader widgets for related widgets to PATHNAME. Return
  1523. the group leader of this widget if None is given."""
  1524. return self.tk.call('wm', 'group', self._w, pathName)
  1525. group = wm_group
  1526. def wm_iconbitmap(self, bitmap=None, default=None):
  1527. """Set bitmap for the iconified widget to BITMAP. Return
  1528. the bitmap if None is given.
  1529. Under Windows, the DEFAULT parameter can be used to set the icon
  1530. for the widget and any descendents that don't have an icon set
  1531. explicitly. DEFAULT can be the relative path to a .ico file
  1532. (example: root.iconbitmap(default='myicon.ico') ). See Tk
  1533. documentation for more information."""
  1534. if default:
  1535. return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
  1536. else:
  1537. return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
  1538. iconbitmap = wm_iconbitmap
  1539. def wm_iconify(self):
  1540. """Display widget as icon."""
  1541. return self.tk.call('wm', 'iconify', self._w)
  1542. iconify = wm_iconify
  1543. def wm_iconmask(self, bitmap=None):
  1544. """Set mask for the icon bitmap of this widget. Return the
  1545. mask if None is given."""
  1546. return self.tk.call('wm', 'iconmask', self._w, bitmap)
  1547. iconmask = wm_iconmask
  1548. def wm_iconname(self, newName=None):
  1549. """Set the name of the icon for this widget. Return the name if
  1550. None is given."""
  1551. return self.tk.call('wm', 'iconname', self._w, newName)
  1552. iconname = wm_iconname
  1553. def wm_iconposition(self, x=None, y=None):
  1554. """Set the position of the icon of this widget to X and Y. Return
  1555. a tuple of the current values of X and X if None is given."""
  1556. return self._getints(self.tk.call(
  1557. 'wm', 'iconposition', self._w, x, y))
  1558. iconposition = wm_iconposition
  1559. def wm_iconwindow(self, pathName=None):
  1560. """Set widget PATHNAME to be displayed instead of icon. Return the current
  1561. value if None is given."""
  1562. return self.tk.call('wm', 'iconwindow', self._w, pathName)
  1563. iconwindow = wm_iconwindow
  1564. def wm_maxsize(self, width=None, height=None):
  1565. """Set max WIDTH and HEIGHT for this widget. If the window is gridded
  1566. the values are given in grid units. Return the current values if None
  1567. is given."""
  1568. return self._getints(self.tk.call(
  1569. 'wm', 'maxsize', self._w, width, height))
  1570. maxsize = wm_maxsize
  1571. def wm_minsize(self, width=None, height=None):
  1572. """Set min WIDTH and HEIGHT for this widget. If the window is gridded
  1573. the values are given in grid units. Return the current values if None
  1574. is given."""
  1575. return self._getints(self.tk.call(
  1576. 'wm', 'minsize', self._w, width, height))
  1577. minsize = wm_minsize
  1578. def wm_overrideredirect(self, boolean=None):
  1579. """Instruct the window manager to ignore this widget
  1580. if BOOLEAN is given with 1. Return the current value if None
  1581. is given."""
  1582. return self._getboolean(self.tk.call(
  1583. 'wm', 'overrideredirect', self._w, boolean))
  1584. overrideredirect = wm_overrideredirect
  1585. def wm_positionfrom(self, who=None):
  1586. """Instruct the window manager that the position of this widget shall
  1587. be defined by the user if WHO is "user", and by its own policy if WHO is
  1588. "program"."""
  1589. return self.tk.call('wm', 'positionfrom', self._w, who)
  1590. positionfrom = wm_positionfrom
  1591. def wm_protocol(self, name=None, func=None):
  1592. """Bind function FUNC to command NAME for this widget.
  1593. Return the function bound to NAME if None is given. NAME could be
  1594. e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
  1595. if hasattr(func, '__call__'):
  1596. command = self._register(func)
  1597. else:
  1598. command = func
  1599. return self.tk.call(
  1600. 'wm', 'protocol', self._w, name, command)
  1601. protocol = wm_protocol
  1602. def wm_resizable(self, width=None, height=None):
  1603. """Instruct the window manager whether this width can be resized
  1604. in WIDTH or HEIGHT. Both values are boolean values."""
  1605. return self.tk.call('wm', 'resizable', self._w, width, height)
  1606. resizable = wm_resizable
  1607. def wm_sizefrom(self, who=None):
  1608. """Instruct the window manager that the size of this widget shall
  1609. be defined by the user if WHO is "user", and by its own policy if WHO is
  1610. "program"."""
  1611. return self.tk.call('wm', 'sizefrom', self._w, who)
  1612. sizefrom = wm_sizefrom
  1613. def wm_state(self, newstate=None):
  1614. """Query or set the state of this widget as one of normal, icon,
  1615. iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
  1616. return self.tk.call('wm', 'state', self._w, newstate)
  1617. state = wm_state
  1618. def wm_title(self, string=None):
  1619. """Set the title of this widget."""
  1620. return self.tk.call('wm', 'title', self._w, string)
  1621. title = wm_title
  1622. def wm_transient(self, master=None):
  1623. """Instruct the window manager that this widget is transient
  1624. with regard to widget MASTER."""
  1625. return self.tk.call('wm', 'transient', self._w, master)
  1626. transient = wm_transient
  1627. def wm_withdraw(self):
  1628. """Withdraw this widget from the screen such that it is unmapped
  1629. and forgotten by the window manager. Re-draw it with wm_deiconify."""
  1630. return self.tk.call('wm', 'withdraw', self._w)
  1631. withdraw = wm_withdraw
  1632. class Tk(Misc, Wm):
  1633. """Toplevel widget of Tk which represents mostly the main window
  1634. of an application. It has an associated Tcl interpreter."""
  1635. _w = '.'
  1636. def __init__(self, screenName=None, baseName=None, className='Tk',
  1637. useTk=1, sync=0, use=None):
  1638. """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
  1639. be created. BASENAME will be used for the identification of the profile file (see
  1640. readprofile).
  1641. It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
  1642. is the name of the widget class."""
  1643. self.master = None
  1644. self.children = {}
  1645. self._tkloaded = 0
  1646. # to avoid recursions in the getattr code in case of failure, we
  1647. # ensure that self.tk is always _something_.
  1648. self.tk = None
  1649. if baseName is None:
  1650. import os
  1651. baseName = os.path.basename(sys.argv[0])
  1652. baseName, ext = os.path.splitext(baseName)
  1653. if ext not in ('.py', '.pyc', '.pyo'):
  1654. baseName = baseName + ext
  1655. interactive = 0
  1656. self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
  1657. if useTk:
  1658. self._loadtk()
  1659. if not sys.flags.ignore_environment:
  1660. # Issue #16248: Honor the -E flag to avoid code injection.
  1661. self.readprofile(baseName, className)
  1662. def loadtk(self):
  1663. if not self._tkloaded:
  1664. self.tk.loadtk()
  1665. self._loadtk()
  1666. def _loadtk(self):
  1667. self._tkloaded = 1
  1668. global _default_root
  1669. # Version sanity checks
  1670. tk_version = self.tk.getvar('tk_version')
  1671. if tk_version != _tkinter.TK_VERSION:
  1672. raise RuntimeError, \
  1673. "tk.h version (%s) doesn't match libtk.a version (%s)" \
  1674. % (_tkinter.TK_VERSION, tk_version)
  1675. # Under unknown circumstances, tcl_version gets coerced to float
  1676. tcl_version = str(self.tk.getvar('tcl_version'))
  1677. if tcl_version != _tkinter.TCL_VERSION:
  1678. raise RuntimeError, \
  1679. "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
  1680. % (_tkinter.TCL_VERSION, tcl_version)
  1681. if TkVersion < 4.0:
  1682. raise RuntimeError, \
  1683. "Tk 4.0 or higher is required; found Tk %s" \
  1684. % str(TkVersion)
  1685. # Create and register the tkerror and exit commands
  1686. # We need to inline parts of _register here, _ register
  1687. # would register differently-named commands.
  1688. if self._tclCommands is None:
  1689. self._tclCommands = []
  1690. self.tk.createcommand('tkerror', _tkerror)
  1691. self.tk.createcommand('exit', _exit)
  1692. self._tclCommands.append('tkerror')
  1693. self._tclCommands.append('exit')
  1694. if _support_default_root and not _default_root:
  1695. _default_root = self
  1696. self.protocol("WM_DELETE_WINDOW", self.destroy)
  1697. def destroy(self):
  1698. """Destroy this and all descendants widgets. This will
  1699. end the application of this Tcl interpreter."""
  1700. for c in self.children.values(): c.destroy()
  1701. self.tk.call('destroy', self._w)
  1702. Misc.destroy(self)
  1703. global _default_root
  1704. if _support_default_root and _default_root is self:
  1705. _default_root = None
  1706. def readprofile(self, baseName, className):
  1707. """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
  1708. the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
  1709. such a file exists in the home directory."""
  1710. import os
  1711. if 'HOME' in os.environ: home = os.environ['HOME']
  1712. else: home = os.curdir
  1713. class_tcl = os.path.join(home, '.%s.tcl' % className)
  1714. class_py = os.path.join(home, '.%s.py' % className)
  1715. base_tcl = os.path.join(home, '.%s.tcl' % baseName)
  1716. base_py = os.path.join(home, '.%s.py' % baseName)
  1717. dir = {'self': self}
  1718. exec 'from Tkinter import *' in dir
  1719. if os.path.isfile(class_tcl):
  1720. self.tk.call('source', class_tcl)
  1721. if os.path.isfile(class_py):
  1722. execfile(class_py, dir)
  1723. if os.path.isfile(base_tcl):
  1724. self.tk.call('source', base_tcl)
  1725. if os.path.isfile(base_py):
  1726. execfile(base_py, dir)
  1727. def report_callback_exception(self, exc, val, tb):
  1728. """Report callback exception on sys.stderr.
  1729. Applications may want to override this internal function, and
  1730. should when sys.stderr is None."""
  1731. import traceback, sys
  1732. print >>sys.stderr, "Exception in Tkinter callback"
  1733. sys.last_type = exc
  1734. sys.last_value = val
  1735. sys.last_traceback = tb
  1736. traceback.print_exception(exc, val, tb)
  1737. def __getattr__(self, attr):
  1738. "Delegate attribute access to the interpreter object"
  1739. return getattr(self.tk, attr)
  1740. # Ideally, the classes Pack, Place and Grid disappear, the
  1741. # pack/place/grid methods are defined on the Widget class, and
  1742. # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
  1743. # ...), with pack(), place() and grid() being short for
  1744. # pack_configure(), place_configure() and grid_columnconfigure(), and
  1745. # forget() being short for pack_forget(). As a practical matter, I'm
  1746. # afraid that there is too much code out there that may be using the
  1747. # Pack, Place or Grid class, so I leave them intact -- but only as
  1748. # backwards compatibility features. Also note that those methods that
  1749. # take a master as argument (e.g. pack_propagate) have been moved to
  1750. # the Misc class (which now incorporates all methods common between
  1751. # toplevel and interior widgets). Again, for compatibility, these are
  1752. # copied into the Pack, Place or Grid class.
  1753. def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
  1754. return Tk(screenName, baseName, className, useTk)
  1755. class Pack:
  1756. """Geometry manager Pack.
  1757. Base class to use the methods pack_* in every widget."""
  1758. def pack_configure(self, cnf={}, **kw):
  1759. """Pack a widget in the parent widget. Use as options:
  1760. after=widget - pack it after you have packed widget
  1761. anchor=NSEW (or subset) - position widget according to
  1762. given direction
  1763. before=widget - pack it before you will pack widget
  1764. expand=bool - expand widget if parent size grows
  1765. fill=NONE or X or Y or BOTH - fill widget if widget grows
  1766. in=master - use master to contain this widget
  1767. in_=master - see 'in' option description
  1768. ipadx=amount - add internal padding in x direction
  1769. ipady=amount - add internal padding in y direction
  1770. padx=amount - add padding in x direction
  1771. pady=amount - add padding in y direction
  1772. side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
  1773. """
  1774. self.tk.call(
  1775. ('pack', 'configure', self._w)
  1776. + self._options(cnf, kw))
  1777. pack = configure = config = pack_configure
  1778. def pack_forget(self):
  1779. """Unmap this widget and do not use it for the packing order."""
  1780. self.tk.call('pack', 'forget', self._w)
  1781. forget = pack_forget
  1782. def pack_info(self):
  1783. """Return information about the packing options
  1784. for this widget."""
  1785. d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w))
  1786. if 'in' in d:
  1787. d['in'] = self.nametowidget(d['in'])
  1788. return d
  1789. info = pack_info
  1790. propagate = pack_propagate = Misc.pack_propagate
  1791. slaves = pack_slaves = Misc.pack_slaves
  1792. class Place:
  1793. """Geometry manager Place.
  1794. Base class to use the methods place_* in every widget."""
  1795. def place_configure(self, cnf={}, **kw):
  1796. """Place a widget in the parent widget. Use as options:
  1797. in=master - master relative to which the widget is placed
  1798. in_=master - see 'in' option description
  1799. x=amount - locate anchor of this widget at position x of master
  1800. y=amount - locate anchor of this widget at position y of master
  1801. relx=amount - locate anchor of this widget between 0.0 and 1.0
  1802. relative to width of master (1.0 is right edge)
  1803. rely=amount - locate anchor of this widget between 0.0 and 1.0
  1804. relative to height of master (1.0 is bottom edge)
  1805. anchor=NSEW (or subset) - position anchor according to given direction
  1806. width=amount - width of this widget in pixel
  1807. height=amount - height of this widget in pixel
  1808. relwidth=amount - width of this widget between 0.0 and 1.0
  1809. relative to width of master (1.0 is the same width
  1810. as the master)
  1811. relheight=amount - height of this widget between 0.0 and 1.0
  1812. relative to height of master (1.0 is the same
  1813. height as the master)
  1814. bordermode="inside" or "outside" - whether to take border width of
  1815. master widget into account
  1816. """
  1817. self.tk.call(
  1818. ('place', 'configure', self._w)
  1819. + self._options(cnf, kw))
  1820. place = configure = config = place_configure
  1821. def place_forget(self):
  1822. """Unmap this widget."""
  1823. self.tk.call('place', 'forget', self._w)
  1824. forget = place_forget
  1825. def place_info(self):
  1826. """Return information about the placing options
  1827. for this widget."""
  1828. d = _splitdict(self.tk, self.tk.call('place', 'info', self._w))
  1829. if 'in' in d:
  1830. d['in'] = self.nametowidget(d['in'])
  1831. return d
  1832. info = place_info
  1833. slaves = place_slaves = Misc.place_slaves
  1834. class Grid:
  1835. """Geometry manager Grid.
  1836. Base class to use the methods grid_* in every widget."""
  1837. # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
  1838. def grid_configure(self, cnf={}, **kw):
  1839. """Position a widget in the parent widget in a grid. Use as options:
  1840. column=number - use cell identified with given column (starting with 0)
  1841. columnspan=number - this widget will span several columns
  1842. in=master - use master to contain this widget
  1843. in_=master - see 'in' option description
  1844. ipadx=amount - add internal padding in x direction
  1845. ipady=amount - add internal padding in y direction
  1846. padx=amount - add padding in x direction
  1847. pady=amount - add padding in y direction
  1848. row=number - use cell identified with given row (starting with 0)
  1849. rowspan=number - this widget will span several rows
  1850. sticky=NSEW - if cell is larger on which sides will this
  1851. widget stick to the cell boundary
  1852. """
  1853. self.tk.call(
  1854. ('grid', 'configure', self._w)
  1855. + self._options(cnf, kw))
  1856. grid = configure = config = grid_configure
  1857. bbox = grid_bbox = Misc.grid_bbox
  1858. columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
  1859. def grid_forget(self):
  1860. """Unmap this widget."""
  1861. self.tk.call('grid', 'forget', self._w)
  1862. forget = grid_forget
  1863. def grid_remove(self):
  1864. """Unmap this widget but remember the grid options."""
  1865. self.tk.call('grid', 'remove', self._w)
  1866. def grid_info(self):
  1867. """Return information about the options
  1868. for positioning this widget in a grid."""
  1869. d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w))
  1870. if 'in' in d:
  1871. d['in'] = self.nametowidget(d['in'])
  1872. return d
  1873. info = grid_info
  1874. location = grid_location = Misc.grid_location
  1875. propagate = grid_propagate = Misc.grid_propagate
  1876. rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
  1877. size = grid_size = Misc.grid_size
  1878. slaves = grid_slaves = Misc.grid_slaves
  1879. class BaseWidget(Misc):
  1880. """Internal class."""
  1881. def _setup(self, master, cnf):
  1882. """Internal function. Sets up information about children."""
  1883. if _support_default_root:
  1884. global _default_root
  1885. if not master:
  1886. if not _default_root:
  1887. _default_root = Tk()
  1888. master = _default_root
  1889. self.master = master
  1890. self.tk = master.tk
  1891. name = None
  1892. if 'name' in cnf:
  1893. name = cnf['name']
  1894. del cnf['name']
  1895. if not name:
  1896. name = repr(id(self))
  1897. self._name = name
  1898. if master._w=='.':
  1899. self._w = '.' + name
  1900. else:
  1901. self._w = master._w + '.' + name
  1902. self.children = {}
  1903. if self._name in self.master.children:
  1904. self.master.children[self._name].destroy()
  1905. self.master.children[self._name] = self
  1906. def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
  1907. """Construct a widget with the parent widget MASTER, a name WIDGETNAME
  1908. and appropriate options."""
  1909. if kw:
  1910. cnf = _cnfmerge((cnf, kw))
  1911. self.widgetName = widgetName
  1912. BaseWidget._setup(self, master, cnf)
  1913. if self._tclCommands is None:
  1914. self._tclCommands = []
  1915. classes = []
  1916. for k in cnf.keys():
  1917. if type(k) is ClassType:
  1918. classes.append((k, cnf[k]))
  1919. del cnf[k]
  1920. self.tk.call(
  1921. (widgetName, self._w) + extra + self._options(cnf))
  1922. for k, v in classes:
  1923. k.configure(self, v)
  1924. def destroy(self):
  1925. """Destroy this and all descendants widgets."""
  1926. for c in self.children.values(): c.destroy()
  1927. self.tk.call('destroy', self._w)
  1928. if self._name in self.master.children:
  1929. del self.master.children[self._name]
  1930. Misc.destroy(self)
  1931. def _do(self, name, args=()):
  1932. # XXX Obsolete -- better use self.tk.call directly!
  1933. return self.tk.call((self._w, name) + args)
  1934. class Widget(BaseWidget, Pack, Place, Grid):
  1935. """Internal class.
  1936. Base class for a widget which can be positioned with the geometry managers
  1937. Pack, Place or Grid."""
  1938. pass
  1939. class Toplevel(BaseWidget, Wm):
  1940. """Toplevel widget, e.g. for dialogs."""
  1941. def __init__(self, master=None, cnf={}, **kw):
  1942. """Construct a toplevel widget with the parent MASTER.
  1943. Valid resource names: background, bd, bg, borderwidth, class,
  1944. colormap, container, cursor, height, highlightbackground,
  1945. highlightcolor, highlightthickness, menu, relief, screen, takefocus,
  1946. use, visual, width."""
  1947. if kw:
  1948. cnf = _cnfmerge((cnf, kw))
  1949. extra = ()
  1950. for wmkey in ['screen', 'class_', 'class', 'visual',
  1951. 'colormap']:
  1952. if wmkey in cnf:
  1953. val = cnf[wmkey]
  1954. # TBD: a hack needed because some keys
  1955. # are not valid as keyword arguments
  1956. if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
  1957. else: opt = '-'+wmkey
  1958. extra = extra + (opt, val)
  1959. del cnf[wmkey]
  1960. BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
  1961. root = self._root()
  1962. self.iconname(root.iconname())
  1963. self.title(root.title())
  1964. self.protocol("WM_DELETE_WINDOW", self.destroy)
  1965. class Button(Widget):
  1966. """Button widget."""
  1967. def __init__(self, master=None, cnf={}, **kw):
  1968. """Construct a button widget with the parent MASTER.
  1969. STANDARD OPTIONS
  1970. activebackground, activeforeground, anchor,
  1971. background, bitmap, borderwidth, cursor,
  1972. disabledforeground, font, foreground
  1973. highlightbackground, highlightcolor,
  1974. highlightthickness, image, justify,
  1975. padx, pady, relief, repeatdelay,
  1976. repeatinterval, takefocus, text,
  1977. textvariable, underline, wraplength
  1978. WIDGET-SPECIFIC OPTIONS
  1979. command, compound, default, height,
  1980. overrelief, state, width
  1981. """
  1982. Widget.__init__(self, master, 'button', cnf, kw)
  1983. def tkButtonEnter(self, *dummy):
  1984. self.tk.call('tkButtonEnter', self._w)
  1985. def tkButtonLeave(self, *dummy):
  1986. self.tk.call('tkButtonLeave', self._w)
  1987. def tkButtonDown(self, *dummy):
  1988. self.tk.call('tkButtonDown', self._w)
  1989. def tkButtonUp(self, *dummy):
  1990. self.tk.call('tkButtonUp', self._w)
  1991. def tkButtonInvoke(self, *dummy):
  1992. self.tk.call('tkButtonInvoke', self._w)
  1993. def flash(self):
  1994. """Flash the button.
  1995. This is accomplished by redisplaying
  1996. the button several times, alternating between active and
  1997. normal colors. At the end of the flash the button is left
  1998. in the same normal/active state as when the command was
  1999. invoked. This command is ignored if the button's state is
  2000. disabled.
  2001. """
  2002. self.tk.call(self._w, 'flash')
  2003. def invoke(self):
  2004. """Invoke the command associated with the button.
  2005. The return value is the return value from the command,
  2006. or an empty string if there is no command associated with
  2007. the button. This command is ignored if the button's state
  2008. is disabled.
  2009. """
  2010. return self.tk.call(self._w, 'invoke')
  2011. # Indices:
  2012. # XXX I don't like these -- take them away
  2013. def AtEnd():
  2014. return 'end'
  2015. def AtInsert(*args):
  2016. s = 'insert'
  2017. for a in args:
  2018. if a: s = s + (' ' + a)
  2019. return s
  2020. def AtSelFirst():
  2021. return 'sel.first'
  2022. def AtSelLast():
  2023. return 'sel.last'
  2024. def At(x, y=None):
  2025. if y is None:
  2026. return '@%r' % (x,)
  2027. else:
  2028. return '@%r,%r' % (x, y)
  2029. class Canvas(Widget, XView, YView):
  2030. """Canvas widget to display graphical elements like lines or text."""
  2031. def __init__(self, master=None, cnf={}, **kw):
  2032. """Construct a canvas widget with the parent MASTER.
  2033. Valid resource names: background, bd, bg, borderwidth, closeenough,
  2034. confine, cursor, height, highlightbackground, highlightcolor,
  2035. highlightthickness, insertbackground, insertborderwidth,
  2036. insertofftime, insertontime, insertwidth, offset, relief,
  2037. scrollregion, selectbackground, selectborderwidth, selectforeground,
  2038. state, takefocus, width, xscrollcommand, xscrollincrement,
  2039. yscrollcommand, yscrollincrement."""
  2040. Widget.__init__(self, master, 'canvas', cnf, kw)
  2041. def addtag(self, *args):
  2042. """Internal function."""
  2043. self.tk.call((self._w, 'addtag') + args)
  2044. def addtag_above(self, newtag, tagOrId):
  2045. """Add tag NEWTAG to all items above TAGORID."""
  2046. self.addtag(newtag, 'above', tagOrId)
  2047. def addtag_all(self, newtag):
  2048. """Add tag NEWTAG to all items."""
  2049. self.addtag(newtag, 'all')
  2050. def addtag_below(self, newtag, tagOrId):
  2051. """Add tag NEWTAG to all items below TAGORID."""
  2052. self.addtag(newtag, 'below', tagOrId)
  2053. def addtag_closest(self, newtag, x, y, halo=None, start=None):
  2054. """Add tag NEWTAG to item which is closest to pixel at X, Y.
  2055. If several match take the top-most.
  2056. All items closer than HALO are considered overlapping (all are
  2057. closests). If START is specified the next below this tag is taken."""
  2058. self.addtag(newtag, 'closest', x, y, halo, start)
  2059. def addtag_enclosed(self, newtag, x1, y1, x2, y2):
  2060. """Add tag NEWTAG to all items in the rectangle defined
  2061. by X1,Y1,X2,Y2."""
  2062. self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
  2063. def addtag_overlapping(self, newtag, x1, y1, x2, y2):
  2064. """Add tag NEWTAG to all items which overlap the rectangle
  2065. defined by X1,Y1,X2,Y2."""
  2066. self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
  2067. def addtag_withtag(self, newtag, tagOrId):
  2068. """Add tag NEWTAG to all items with TAGORID."""
  2069. self.addtag(newtag, 'withtag', tagOrId)
  2070. def bbox(self, *args):
  2071. """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2072. which encloses all items with tags specified as arguments."""
  2073. return self._getints(
  2074. self.tk.call((self._w, 'bbox') + args)) or None
  2075. def tag_unbind(self, tagOrId, sequence, funcid=None):
  2076. """Unbind for all items with TAGORID for event SEQUENCE the
  2077. function identified with FUNCID."""
  2078. self.tk.call(self._w, 'bind', tagOrId, sequence, '')
  2079. if funcid:
  2080. self.deletecommand(funcid)
  2081. def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
  2082. """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
  2083. An additional boolean parameter ADD specifies whether FUNC will be
  2084. called additionally to the other bound function or whether it will
  2085. replace the previous function. See bind for the return value."""
  2086. return self._bind((self._w, 'bind', tagOrId),
  2087. sequence, func, add)
  2088. def canvasx(self, screenx, gridspacing=None):
  2089. """Return the canvas x coordinate of pixel position SCREENX rounded
  2090. to nearest multiple of GRIDSPACING units."""
  2091. return getdouble(self.tk.call(
  2092. self._w, 'canvasx', screenx, gridspacing))
  2093. def canvasy(self, screeny, gridspacing=None):
  2094. """Return the canvas y coordinate of pixel position SCREENY rounded
  2095. to nearest multiple of GRIDSPACING units."""
  2096. return getdouble(self.tk.call(
  2097. self._w, 'canvasy', screeny, gridspacing))
  2098. def coords(self, *args):
  2099. """Return a list of coordinates for the item given in ARGS."""
  2100. # XXX Should use _flatten on args
  2101. return map(getdouble,
  2102. self.tk.splitlist(
  2103. self.tk.call((self._w, 'coords') + args)))
  2104. def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
  2105. """Internal function."""
  2106. args = _flatten(args)
  2107. cnf = args[-1]
  2108. if type(cnf) in (DictionaryType, TupleType):
  2109. args = args[:-1]
  2110. else:
  2111. cnf = {}
  2112. return getint(self.tk.call(
  2113. self._w, 'create', itemType,
  2114. *(args + self._options(cnf, kw))))
  2115. def create_arc(self, *args, **kw):
  2116. """Create arc shaped region with coordinates x1,y1,x2,y2."""
  2117. return self._create('arc', args, kw)
  2118. def create_bitmap(self, *args, **kw):
  2119. """Create bitmap with coordinates x1,y1."""
  2120. return self._create('bitmap', args, kw)
  2121. def create_image(self, *args, **kw):
  2122. """Create image item with coordinates x1,y1."""
  2123. return self._create('image', args, kw)
  2124. def create_line(self, *args, **kw):
  2125. """Create line with coordinates x1,y1,...,xn,yn."""
  2126. return self._create('line', args, kw)
  2127. def create_oval(self, *args, **kw):
  2128. """Create oval with coordinates x1,y1,x2,y2."""
  2129. return self._create('oval', args, kw)
  2130. def create_polygon(self, *args, **kw):
  2131. """Create polygon with coordinates x1,y1,...,xn,yn."""
  2132. return self._create('polygon', args, kw)
  2133. def create_rectangle(self, *args, **kw):
  2134. """Create rectangle with coordinates x1,y1,x2,y2."""
  2135. return self._create('rectangle', args, kw)
  2136. def create_text(self, *args, **kw):
  2137. """Create text with coordinates x1,y1."""
  2138. return self._create('text', args, kw)
  2139. def create_window(self, *args, **kw):
  2140. """Create window with coordinates x1,y1,x2,y2."""
  2141. return self._create('window', args, kw)
  2142. def dchars(self, *args):
  2143. """Delete characters of text items identified by tag or id in ARGS (possibly
  2144. several times) from FIRST to LAST character (including)."""
  2145. self.tk.call((self._w, 'dchars') + args)
  2146. def delete(self, *args):
  2147. """Delete items identified by all tag or ids contained in ARGS."""
  2148. self.tk.call((self._w, 'delete') + args)
  2149. def dtag(self, *args):
  2150. """Delete tag or id given as last arguments in ARGS from items
  2151. identified by first argument in ARGS."""
  2152. self.tk.call((self._w, 'dtag') + args)
  2153. def find(self, *args):
  2154. """Internal function."""
  2155. return self._getints(
  2156. self.tk.call((self._w, 'find') + args)) or ()
  2157. def find_above(self, tagOrId):
  2158. """Return items above TAGORID."""
  2159. return self.find('above', tagOrId)
  2160. def find_all(self):
  2161. """Return all items."""
  2162. return self.find('all')
  2163. def find_below(self, tagOrId):
  2164. """Return all items below TAGORID."""
  2165. return self.find('below', tagOrId)
  2166. def find_closest(self, x, y, halo=None, start=None):
  2167. """Return item which is closest to pixel at X, Y.
  2168. If several match take the top-most.
  2169. All items closer than HALO are considered overlapping (all are
  2170. closests). If START is specified the next below this tag is taken."""
  2171. return self.find('closest', x, y, halo, start)
  2172. def find_enclosed(self, x1, y1, x2, y2):
  2173. """Return all items in rectangle defined
  2174. by X1,Y1,X2,Y2."""
  2175. return self.find('enclosed', x1, y1, x2, y2)
  2176. def find_overlapping(self, x1, y1, x2, y2):
  2177. """Return all items which overlap the rectangle
  2178. defined by X1,Y1,X2,Y2."""
  2179. return self.find('overlapping', x1, y1, x2, y2)
  2180. def find_withtag(self, tagOrId):
  2181. """Return all items with TAGORID."""
  2182. return self.find('withtag', tagOrId)
  2183. def focus(self, *args):
  2184. """Set focus to the first item specified in ARGS."""
  2185. return self.tk.call((self._w, 'focus') + args)
  2186. def gettags(self, *args):
  2187. """Return tags associated with the first item specified in ARGS."""
  2188. return self.tk.splitlist(
  2189. self.tk.call((self._w, 'gettags') + args))
  2190. def icursor(self, *args):
  2191. """Set cursor at position POS in the item identified by TAGORID.
  2192. In ARGS TAGORID must be first."""
  2193. self.tk.call((self._w, 'icursor') + args)
  2194. def index(self, *args):
  2195. """Return position of cursor as integer in item specified in ARGS."""
  2196. return getint(self.tk.call((self._w, 'index') + args))
  2197. def insert(self, *args):
  2198. """Insert TEXT in item TAGORID at position POS. ARGS must
  2199. be TAGORID POS TEXT."""
  2200. self.tk.call((self._w, 'insert') + args)
  2201. def itemcget(self, tagOrId, option):
  2202. """Return the resource value for an OPTION for item TAGORID."""
  2203. return self.tk.call(
  2204. (self._w, 'itemcget') + (tagOrId, '-'+option))
  2205. def itemconfigure(self, tagOrId, cnf=None, **kw):
  2206. """Configure resources of an item TAGORID.
  2207. The values for resources are specified as keyword
  2208. arguments. To get an overview about
  2209. the allowed keyword arguments call the method without arguments.
  2210. """
  2211. return self._configure(('itemconfigure', tagOrId), cnf, kw)
  2212. itemconfig = itemconfigure
  2213. # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
  2214. # so the preferred name for them is tag_lower, tag_raise
  2215. # (similar to tag_bind, and similar to the Text widget);
  2216. # unfortunately can't delete the old ones yet (maybe in 1.6)
  2217. def tag_lower(self, *args):
  2218. """Lower an item TAGORID given in ARGS
  2219. (optional below another item)."""
  2220. self.tk.call((self._w, 'lower') + args)
  2221. lower = tag_lower
  2222. def move(self, *args):
  2223. """Move an item TAGORID given in ARGS."""
  2224. self.tk.call((self._w, 'move') + args)
  2225. def postscript(self, cnf={}, **kw):
  2226. """Print the contents of the canvas to a postscript
  2227. file. Valid options: colormap, colormode, file, fontmap,
  2228. height, pageanchor, pageheight, pagewidth, pagex, pagey,
  2229. rotate, witdh, x, y."""
  2230. return self.tk.call((self._w, 'postscript') +
  2231. self._options(cnf, kw))
  2232. def tag_raise(self, *args):
  2233. """Raise an item TAGORID given in ARGS
  2234. (optional above another item)."""
  2235. self.tk.call((self._w, 'raise') + args)
  2236. lift = tkraise = tag_raise
  2237. def scale(self, *args):
  2238. """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
  2239. self.tk.call((self._w, 'scale') + args)
  2240. def scan_mark(self, x, y):
  2241. """Remember the current X, Y coordinates."""
  2242. self.tk.call(self._w, 'scan', 'mark', x, y)
  2243. def scan_dragto(self, x, y, gain=10):
  2244. """Adjust the view of the canvas to GAIN times the
  2245. difference between X and Y and the coordinates given in
  2246. scan_mark."""
  2247. self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
  2248. def select_adjust(self, tagOrId, index):
  2249. """Adjust the end of the selection near the cursor of an item TAGORID to index."""
  2250. self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
  2251. def select_clear(self):
  2252. """Clear the selection if it is in this widget."""
  2253. self.tk.call(self._w, 'select', 'clear')
  2254. def select_from(self, tagOrId, index):
  2255. """Set the fixed end of a selection in item TAGORID to INDEX."""
  2256. self.tk.call(self._w, 'select', 'from', tagOrId, index)
  2257. def select_item(self):
  2258. """Return the item which has the selection."""
  2259. return self.tk.call(self._w, 'select', 'item') or None
  2260. def select_to(self, tagOrId, index):
  2261. """Set the variable end of a selection in item TAGORID to INDEX."""
  2262. self.tk.call(self._w, 'select', 'to', tagOrId, index)
  2263. def type(self, tagOrId):
  2264. """Return the type of the item TAGORID."""
  2265. return self.tk.call(self._w, 'type', tagOrId) or None
  2266. class Checkbutton(Widget):
  2267. """Checkbutton widget which is either in on- or off-state."""
  2268. def __init__(self, master=None, cnf={}, **kw):
  2269. """Construct a checkbutton widget with the parent MASTER.
  2270. Valid resource names: activebackground, activeforeground, anchor,
  2271. background, bd, bg, bitmap, borderwidth, command, cursor,
  2272. disabledforeground, fg, font, foreground, height,
  2273. highlightbackground, highlightcolor, highlightthickness, image,
  2274. indicatoron, justify, offvalue, onvalue, padx, pady, relief,
  2275. selectcolor, selectimage, state, takefocus, text, textvariable,
  2276. underline, variable, width, wraplength."""
  2277. Widget.__init__(self, master, 'checkbutton', cnf, kw)
  2278. def deselect(self):
  2279. """Put the button in off-state."""
  2280. self.tk.call(self._w, 'deselect')
  2281. def flash(self):
  2282. """Flash the button."""
  2283. self.tk.call(self._w, 'flash')
  2284. def invoke(self):
  2285. """Toggle the button and invoke a command if given as resource."""
  2286. return self.tk.call(self._w, 'invoke')
  2287. def select(self):
  2288. """Put the button in on-state."""
  2289. self.tk.call(self._w, 'select')
  2290. def toggle(self):
  2291. """Toggle the button."""
  2292. self.tk.call(self._w, 'toggle')
  2293. class Entry(Widget, XView):
  2294. """Entry widget which allows displaying simple text."""
  2295. def __init__(self, master=None, cnf={}, **kw):
  2296. """Construct an entry widget with the parent MASTER.
  2297. Valid resource names: background, bd, bg, borderwidth, cursor,
  2298. exportselection, fg, font, foreground, highlightbackground,
  2299. highlightcolor, highlightthickness, insertbackground,
  2300. insertborderwidth, insertofftime, insertontime, insertwidth,
  2301. invalidcommand, invcmd, justify, relief, selectbackground,
  2302. selectborderwidth, selectforeground, show, state, takefocus,
  2303. textvariable, validate, validatecommand, vcmd, width,
  2304. xscrollcommand."""
  2305. Widget.__init__(self, master, 'entry', cnf, kw)
  2306. def delete(self, first, last=None):
  2307. """Delete text from FIRST to LAST (not included)."""
  2308. self.tk.call(self._w, 'delete', first, last)
  2309. def get(self):
  2310. """Return the text."""
  2311. return self.tk.call(self._w, 'get')
  2312. def icursor(self, index):
  2313. """Insert cursor at INDEX."""
  2314. self.tk.call(self._w, 'icursor', index)
  2315. def index(self, index):
  2316. """Return position of cursor."""
  2317. return getint(self.tk.call(
  2318. self._w, 'index', index))
  2319. def insert(self, index, string):
  2320. """Insert STRING at INDEX."""
  2321. self.tk.call(self._w, 'insert', index, string)
  2322. def scan_mark(self, x):
  2323. """Remember the current X, Y coordinates."""
  2324. self.tk.call(self._w, 'scan', 'mark', x)
  2325. def scan_dragto(self, x):
  2326. """Adjust the view of the canvas to 10 times the
  2327. difference between X and Y and the coordinates given in
  2328. scan_mark."""
  2329. self.tk.call(self._w, 'scan', 'dragto', x)
  2330. def selection_adjust(self, index):
  2331. """Adjust the end of the selection near the cursor to INDEX."""
  2332. self.tk.call(self._w, 'selection', 'adjust', index)
  2333. select_adjust = selection_adjust
  2334. def selection_clear(self):
  2335. """Clear the selection if it is in this widget."""
  2336. self.tk.call(self._w, 'selection', 'clear')
  2337. select_clear = selection_clear
  2338. def selection_from(self, index):
  2339. """Set the fixed end of a selection to INDEX."""
  2340. self.tk.call(self._w, 'selection', 'from', index)
  2341. select_from = selection_from
  2342. def selection_present(self):
  2343. """Return True if there are characters selected in the entry, False
  2344. otherwise."""
  2345. return self.tk.getboolean(
  2346. self.tk.call(self._w, 'selection', 'present'))
  2347. select_present = selection_present
  2348. def selection_range(self, start, end):
  2349. """Set the selection from START to END (not included)."""
  2350. self.tk.call(self._w, 'selection', 'range', start, end)
  2351. select_range = selection_range
  2352. def selection_to(self, index):
  2353. """Set the variable end of a selection to INDEX."""
  2354. self.tk.call(self._w, 'selection', 'to', index)
  2355. select_to = selection_to
  2356. class Frame(Widget):
  2357. """Frame widget which may contain other widgets and can have a 3D border."""
  2358. def __init__(self, master=None, cnf={}, **kw):
  2359. """Construct a frame widget with the parent MASTER.
  2360. Valid resource names: background, bd, bg, borderwidth, class,
  2361. colormap, container, cursor, height, highlightbackground,
  2362. highlightcolor, highlightthickness, relief, takefocus, visual, width."""
  2363. cnf = _cnfmerge((cnf, kw))
  2364. extra = ()
  2365. if 'class_' in cnf:
  2366. extra = ('-class', cnf['class_'])
  2367. del cnf['class_']
  2368. elif 'class' in cnf:
  2369. extra = ('-class', cnf['class'])
  2370. del cnf['class']
  2371. Widget.__init__(self, master, 'frame', cnf, {}, extra)
  2372. class Label(Widget):
  2373. """Label widget which can display text and bitmaps."""
  2374. def __init__(self, master=None, cnf={}, **kw):
  2375. """Construct a label widget with the parent MASTER.
  2376. STANDARD OPTIONS
  2377. activebackground, activeforeground, anchor,
  2378. background, bitmap, borderwidth, cursor,
  2379. disabledforeground, font, foreground,
  2380. highlightbackground, highlightcolor,
  2381. highlightthickness, image, justify,
  2382. padx, pady, relief, takefocus, text,
  2383. textvariable, underline, wraplength
  2384. WIDGET-SPECIFIC OPTIONS
  2385. height, state, width
  2386. """
  2387. Widget.__init__(self, master, 'label', cnf, kw)
  2388. class Listbox(Widget, XView, YView):
  2389. """Listbox widget which can display a list of strings."""
  2390. def __init__(self, master=None, cnf={}, **kw):
  2391. """Construct a listbox widget with the parent MASTER.
  2392. Valid resource names: background, bd, bg, borderwidth, cursor,
  2393. exportselection, fg, font, foreground, height, highlightbackground,
  2394. highlightcolor, highlightthickness, relief, selectbackground,
  2395. selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
  2396. width, xscrollcommand, yscrollcommand, listvariable."""
  2397. Widget.__init__(self, master, 'listbox', cnf, kw)
  2398. def activate(self, index):
  2399. """Activate item identified by INDEX."""
  2400. self.tk.call(self._w, 'activate', index)
  2401. def bbox(self, index):
  2402. """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2403. which encloses the item identified by the given index."""
  2404. return self._getints(self.tk.call(self._w, 'bbox', index)) or None
  2405. def curselection(self):
  2406. """Return the indices of currently selected item."""
  2407. return self._getints(self.tk.call(self._w, 'curselection')) or ()
  2408. def delete(self, first, last=None):
  2409. """Delete items from FIRST to LAST (included)."""
  2410. self.tk.call(self._w, 'delete', first, last)
  2411. def get(self, first, last=None):
  2412. """Get list of items from FIRST to LAST (included)."""
  2413. if last is not None:
  2414. return self.tk.splitlist(self.tk.call(
  2415. self._w, 'get', first, last))
  2416. else:
  2417. return self.tk.call(self._w, 'get', first)
  2418. def index(self, index):
  2419. """Return index of item identified with INDEX."""
  2420. i = self.tk.call(self._w, 'index', index)
  2421. if i == 'none': return None
  2422. return getint(i)
  2423. def insert(self, index, *elements):
  2424. """Insert ELEMENTS at INDEX."""
  2425. self.tk.call((self._w, 'insert', index) + elements)
  2426. def nearest(self, y):
  2427. """Get index of item which is nearest to y coordinate Y."""
  2428. return getint(self.tk.call(
  2429. self._w, 'nearest', y))
  2430. def scan_mark(self, x, y):
  2431. """Remember the current X, Y coordinates."""
  2432. self.tk.call(self._w, 'scan', 'mark', x, y)
  2433. def scan_dragto(self, x, y):
  2434. """Adjust the view of the listbox to 10 times the
  2435. difference between X and Y and the coordinates given in
  2436. scan_mark."""
  2437. self.tk.call(self._w, 'scan', 'dragto', x, y)
  2438. def see(self, index):
  2439. """Scroll such that INDEX is visible."""
  2440. self.tk.call(self._w, 'see', index)
  2441. def selection_anchor(self, index):
  2442. """Set the fixed end oft the selection to INDEX."""
  2443. self.tk.call(self._w, 'selection', 'anchor', index)
  2444. select_anchor = selection_anchor
  2445. def selection_clear(self, first, last=None):
  2446. """Clear the selection from FIRST to LAST (included)."""
  2447. self.tk.call(self._w,
  2448. 'selection', 'clear', first, last)
  2449. select_clear = selection_clear
  2450. def selection_includes(self, index):
  2451. """Return 1 if INDEX is part of the selection."""
  2452. return self.tk.getboolean(self.tk.call(
  2453. self._w, 'selection', 'includes', index))
  2454. select_includes = selection_includes
  2455. def selection_set(self, first, last=None):
  2456. """Set the selection from FIRST to LAST (included) without
  2457. changing the currently selected elements."""
  2458. self.tk.call(self._w, 'selection', 'set', first, last)
  2459. select_set = selection_set
  2460. def size(self):
  2461. """Return the number of elements in the listbox."""
  2462. return getint(self.tk.call(self._w, 'size'))
  2463. def itemcget(self, index, option):
  2464. """Return the resource value for an ITEM and an OPTION."""
  2465. return self.tk.call(
  2466. (self._w, 'itemcget') + (index, '-'+option))
  2467. def itemconfigure(self, index, cnf=None, **kw):
  2468. """Configure resources of an ITEM.
  2469. The values for resources are specified as keyword arguments.
  2470. To get an overview about the allowed keyword arguments
  2471. call the method without arguments.
  2472. Valid resource names: background, bg, foreground, fg,
  2473. selectbackground, selectforeground."""
  2474. return self._configure(('itemconfigure', index), cnf, kw)
  2475. itemconfig = itemconfigure
  2476. class Menu(Widget):
  2477. """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus."""
  2478. def __init__(self, master=None, cnf={}, **kw):
  2479. """Construct menu widget with the parent MASTER.
  2480. Valid resource names: activebackground, activeborderwidth,
  2481. activeforeground, background, bd, bg, borderwidth, cursor,
  2482. disabledforeground, fg, font, foreground, postcommand, relief,
  2483. selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
  2484. Widget.__init__(self, master, 'menu', cnf, kw)
  2485. def tk_bindForTraversal(self):
  2486. # obsolete since Tk 4.0
  2487. import warnings
  2488. warnings.warn('tk_bindForTraversal() does nothing and '
  2489. 'will be removed in 3.6',
  2490. DeprecationWarning, stacklevel=2)
  2491. def tk_mbPost(self):
  2492. self.tk.call('tk_mbPost', self._w)
  2493. def tk_mbUnpost(self):
  2494. self.tk.call('tk_mbUnpost')
  2495. def tk_traverseToMenu(self, char):
  2496. self.tk.call('tk_traverseToMenu', self._w, char)
  2497. def tk_traverseWithinMenu(self, char):
  2498. self.tk.call('tk_traverseWithinMenu', self._w, char)
  2499. def tk_getMenuButtons(self):
  2500. return self.tk.call('tk_getMenuButtons', self._w)
  2501. def tk_nextMenu(self, count):
  2502. self.tk.call('tk_nextMenu', count)
  2503. def tk_nextMenuEntry(self, count):
  2504. self.tk.call('tk_nextMenuEntry', count)
  2505. def tk_invokeMenu(self):
  2506. self.tk.call('tk_invokeMenu', self._w)
  2507. def tk_firstMenu(self):
  2508. self.tk.call('tk_firstMenu', self._w)
  2509. def tk_mbButtonDown(self):
  2510. self.tk.call('tk_mbButtonDown', self._w)
  2511. def tk_popup(self, x, y, entry=""):
  2512. """Post the menu at position X,Y with entry ENTRY."""
  2513. self.tk.call('tk_popup', self._w, x, y, entry)
  2514. def activate(self, index):
  2515. """Activate entry at INDEX."""
  2516. self.tk.call(self._w, 'activate', index)
  2517. def add(self, itemType, cnf={}, **kw):
  2518. """Internal function."""
  2519. self.tk.call((self._w, 'add', itemType) +
  2520. self._options(cnf, kw))
  2521. def add_cascade(self, cnf={}, **kw):
  2522. """Add hierarchical menu item."""
  2523. self.add('cascade', cnf or kw)
  2524. def add_checkbutton(self, cnf={}, **kw):
  2525. """Add checkbutton menu item."""
  2526. self.add('checkbutton', cnf or kw)
  2527. def add_command(self, cnf={}, **kw):
  2528. """Add command menu item."""
  2529. self.add('command', cnf or kw)
  2530. def add_radiobutton(self, cnf={}, **kw):
  2531. """Addd radio menu item."""
  2532. self.add('radiobutton', cnf or kw)
  2533. def add_separator(self, cnf={}, **kw):
  2534. """Add separator."""
  2535. self.add('separator', cnf or kw)
  2536. def insert(self, index, itemType, cnf={}, **kw):
  2537. """Internal function."""
  2538. self.tk.call((self._w, 'insert', index, itemType) +
  2539. self._options(cnf, kw))
  2540. def insert_cascade(self, index, cnf={}, **kw):
  2541. """Add hierarchical menu item at INDEX."""
  2542. self.insert(index, 'cascade', cnf or kw)
  2543. def insert_checkbutton(self, index, cnf={}, **kw):
  2544. """Add checkbutton menu item at INDEX."""
  2545. self.insert(index, 'checkbutton', cnf or kw)
  2546. def insert_command(self, index, cnf={}, **kw):
  2547. """Add command menu item at INDEX."""
  2548. self.insert(index, 'command', cnf or kw)
  2549. def insert_radiobutton(self, index, cnf={}, **kw):
  2550. """Addd radio menu item at INDEX."""
  2551. self.insert(index, 'radiobutton', cnf or kw)
  2552. def insert_separator(self, index, cnf={}, **kw):
  2553. """Add separator at INDEX."""
  2554. self.insert(index, 'separator', cnf or kw)
  2555. def delete(self, index1, index2=None):
  2556. """Delete menu items between INDEX1 and INDEX2 (included)."""
  2557. if index2 is None:
  2558. index2 = index1
  2559. num_index1, num_index2 = self.index(index1), self.index(index2)
  2560. if (num_index1 is None) or (num_index2 is None):
  2561. num_index1, num_index2 = 0, -1
  2562. for i in range(num_index1, num_index2 + 1):
  2563. if 'command' in self.entryconfig(i):
  2564. c = str(self.entrycget(i, 'command'))
  2565. if c:
  2566. self.deletecommand(c)
  2567. self.tk.call(self._w, 'delete', index1, index2)
  2568. def entrycget(self, index, option):
  2569. """Return the resource value of a menu item for OPTION at INDEX."""
  2570. return self.tk.call(self._w, 'entrycget', index, '-' + option)
  2571. def entryconfigure(self, index, cnf=None, **kw):
  2572. """Configure a menu item at INDEX."""
  2573. return self._configure(('entryconfigure', index), cnf, kw)
  2574. entryconfig = entryconfigure
  2575. def index(self, index):
  2576. """Return the index of a menu item identified by INDEX."""
  2577. i = self.tk.call(self._w, 'index', index)
  2578. if i == 'none': return None
  2579. return getint(i)
  2580. def invoke(self, index):
  2581. """Invoke a menu item identified by INDEX and execute
  2582. the associated command."""
  2583. return self.tk.call(self._w, 'invoke', index)
  2584. def post(self, x, y):
  2585. """Display a menu at position X,Y."""
  2586. self.tk.call(self._w, 'post', x, y)
  2587. def type(self, index):
  2588. """Return the type of the menu item at INDEX."""
  2589. return self.tk.call(self._w, 'type', index)
  2590. def unpost(self):
  2591. """Unmap a menu."""
  2592. self.tk.call(self._w, 'unpost')
  2593. def yposition(self, index):
  2594. """Return the y-position of the topmost pixel of the menu item at INDEX."""
  2595. return getint(self.tk.call(
  2596. self._w, 'yposition', index))
  2597. class Menubutton(Widget):
  2598. """Menubutton widget, obsolete since Tk8.0."""
  2599. def __init__(self, master=None, cnf={}, **kw):
  2600. Widget.__init__(self, master, 'menubutton', cnf, kw)
  2601. class Message(Widget):
  2602. """Message widget to display multiline text. Obsolete since Label does it too."""
  2603. def __init__(self, master=None, cnf={}, **kw):
  2604. Widget.__init__(self, master, 'message', cnf, kw)
  2605. class Radiobutton(Widget):
  2606. """Radiobutton widget which shows only one of several buttons in on-state."""
  2607. def __init__(self, master=None, cnf={}, **kw):
  2608. """Construct a radiobutton widget with the parent MASTER.
  2609. Valid resource names: activebackground, activeforeground, anchor,
  2610. background, bd, bg, bitmap, borderwidth, command, cursor,
  2611. disabledforeground, fg, font, foreground, height,
  2612. highlightbackground, highlightcolor, highlightthickness, image,
  2613. indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
  2614. state, takefocus, text, textvariable, underline, value, variable,
  2615. width, wraplength."""
  2616. Widget.__init__(self, master, 'radiobutton', cnf, kw)
  2617. def deselect(self):
  2618. """Put the button in off-state."""
  2619. self.tk.call(self._w, 'deselect')
  2620. def flash(self):
  2621. """Flash the button."""
  2622. self.tk.call(self._w, 'flash')
  2623. def invoke(self):
  2624. """Toggle the button and invoke a command if given as resource."""
  2625. return self.tk.call(self._w, 'invoke')
  2626. def select(self):
  2627. """Put the button in on-state."""
  2628. self.tk.call(self._w, 'select')
  2629. class Scale(Widget):
  2630. """Scale widget which can display a numerical scale."""
  2631. def __init__(self, master=None, cnf={}, **kw):
  2632. """Construct a scale widget with the parent MASTER.
  2633. Valid resource names: activebackground, background, bigincrement, bd,
  2634. bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
  2635. highlightbackground, highlightcolor, highlightthickness, label,
  2636. length, orient, relief, repeatdelay, repeatinterval, resolution,
  2637. showvalue, sliderlength, sliderrelief, state, takefocus,
  2638. tickinterval, to, troughcolor, variable, width."""
  2639. Widget.__init__(self, master, 'scale', cnf, kw)
  2640. def get(self):
  2641. """Get the current value as integer or float."""
  2642. value = self.tk.call(self._w, 'get')
  2643. try:
  2644. return getint(value)
  2645. except ValueError:
  2646. return getdouble(value)
  2647. def set(self, value):
  2648. """Set the value to VALUE."""
  2649. self.tk.call(self._w, 'set', value)
  2650. def coords(self, value=None):
  2651. """Return a tuple (X,Y) of the point along the centerline of the
  2652. trough that corresponds to VALUE or the current value if None is
  2653. given."""
  2654. return self._getints(self.tk.call(self._w, 'coords', value))
  2655. def identify(self, x, y):
  2656. """Return where the point X,Y lies. Valid return values are "slider",
  2657. "though1" and "though2"."""
  2658. return self.tk.call(self._w, 'identify', x, y)
  2659. class Scrollbar(Widget):
  2660. """Scrollbar widget which displays a slider at a certain position."""
  2661. def __init__(self, master=None, cnf={}, **kw):
  2662. """Construct a scrollbar widget with the parent MASTER.
  2663. Valid resource names: activebackground, activerelief,
  2664. background, bd, bg, borderwidth, command, cursor,
  2665. elementborderwidth, highlightbackground,
  2666. highlightcolor, highlightthickness, jump, orient,
  2667. relief, repeatdelay, repeatinterval, takefocus,
  2668. troughcolor, width."""
  2669. Widget.__init__(self, master, 'scrollbar', cnf, kw)
  2670. def activate(self, index):
  2671. """Display the element at INDEX with activebackground and activerelief.
  2672. INDEX can be "arrow1","slider" or "arrow2"."""
  2673. self.tk.call(self._w, 'activate', index)
  2674. def delta(self, deltax, deltay):
  2675. """Return the fractional change of the scrollbar setting if it
  2676. would be moved by DELTAX or DELTAY pixels."""
  2677. return getdouble(
  2678. self.tk.call(self._w, 'delta', deltax, deltay))
  2679. def fraction(self, x, y):
  2680. """Return the fractional value which corresponds to a slider
  2681. position of X,Y."""
  2682. return getdouble(self.tk.call(self._w, 'fraction', x, y))
  2683. def identify(self, x, y):
  2684. """Return the element under position X,Y as one of
  2685. "arrow1","slider","arrow2" or ""."""
  2686. return self.tk.call(self._w, 'identify', x, y)
  2687. def get(self):
  2688. """Return the current fractional values (upper and lower end)
  2689. of the slider position."""
  2690. return self._getdoubles(self.tk.call(self._w, 'get'))
  2691. def set(self, *args):
  2692. """Set the fractional values of the slider position (upper and
  2693. lower ends as value between 0 and 1)."""
  2694. self.tk.call((self._w, 'set') + args)
  2695. class Text(Widget, XView, YView):
  2696. """Text widget which can display text in various forms."""
  2697. def __init__(self, master=None, cnf={}, **kw):
  2698. """Construct a text widget with the parent MASTER.
  2699. STANDARD OPTIONS
  2700. background, borderwidth, cursor,
  2701. exportselection, font, foreground,
  2702. highlightbackground, highlightcolor,
  2703. highlightthickness, insertbackground,
  2704. insertborderwidth, insertofftime,
  2705. insertontime, insertwidth, padx, pady,
  2706. relief, selectbackground,
  2707. selectborderwidth, selectforeground,
  2708. setgrid, takefocus,
  2709. xscrollcommand, yscrollcommand,
  2710. WIDGET-SPECIFIC OPTIONS
  2711. autoseparators, height, maxundo,
  2712. spacing1, spacing2, spacing3,
  2713. state, tabs, undo, width, wrap,
  2714. """
  2715. Widget.__init__(self, master, 'text', cnf, kw)
  2716. def bbox(self, *args):
  2717. """Return a tuple of (x,y,width,height) which gives the bounding
  2718. box of the visible part of the character at the index in ARGS."""
  2719. return self._getints(
  2720. self.tk.call((self._w, 'bbox') + args)) or None
  2721. def tk_textSelectTo(self, index):
  2722. self.tk.call('tk_textSelectTo', self._w, index)
  2723. def tk_textBackspace(self):
  2724. self.tk.call('tk_textBackspace', self._w)
  2725. def tk_textIndexCloser(self, a, b, c):
  2726. self.tk.call('tk_textIndexCloser', self._w, a, b, c)
  2727. def tk_textResetAnchor(self, index):
  2728. self.tk.call('tk_textResetAnchor', self._w, index)
  2729. def compare(self, index1, op, index2):
  2730. """Return whether between index INDEX1 and index INDEX2 the
  2731. relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
  2732. return self.tk.getboolean(self.tk.call(
  2733. self._w, 'compare', index1, op, index2))
  2734. def debug(self, boolean=None):
  2735. """Turn on the internal consistency checks of the B-Tree inside the text
  2736. widget according to BOOLEAN."""
  2737. if boolean is None:
  2738. return self.tk.getboolean(self.tk.call(self._w, 'debug'))
  2739. self.tk.call(self._w, 'debug', boolean)
  2740. def delete(self, index1, index2=None):
  2741. """Delete the characters between INDEX1 and INDEX2 (not included)."""
  2742. self.tk.call(self._w, 'delete', index1, index2)
  2743. def dlineinfo(self, index):
  2744. """Return tuple (x,y,width,height,baseline) giving the bounding box
  2745. and baseline position of the visible part of the line containing
  2746. the character at INDEX."""
  2747. return self._getints(self.tk.call(self._w, 'dlineinfo', index))
  2748. def dump(self, index1, index2=None, command=None, **kw):
  2749. """Return the contents of the widget between index1 and index2.
  2750. The type of contents returned in filtered based on the keyword
  2751. parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
  2752. given and true, then the corresponding items are returned. The result
  2753. is a list of triples of the form (key, value, index). If none of the
  2754. keywords are true then 'all' is used by default.
  2755. If the 'command' argument is given, it is called once for each element
  2756. of the list of triples, with the values of each triple serving as the
  2757. arguments to the function. In this case the list is not returned."""
  2758. args = []
  2759. func_name = None
  2760. result = None
  2761. if not command:
  2762. # Never call the dump command without the -command flag, since the
  2763. # output could involve Tcl quoting and would be a pain to parse
  2764. # right. Instead just set the command to build a list of triples
  2765. # as if we had done the parsing.
  2766. result = []
  2767. def append_triple(key, value, index, result=result):
  2768. result.append((key, value, index))
  2769. command = append_triple
  2770. try:
  2771. if not isinstance(command, str):
  2772. func_name = command = self._register(command)
  2773. args += ["-command", command]
  2774. for key in kw:
  2775. if kw[key]: args.append("-" + key)
  2776. args.append(index1)
  2777. if index2:
  2778. args.append(index2)
  2779. self.tk.call(self._w, "dump", *args)
  2780. return result
  2781. finally:
  2782. if func_name:
  2783. self.deletecommand(func_name)
  2784. ## new in tk8.4
  2785. def edit(self, *args):
  2786. """Internal method
  2787. This method controls the undo mechanism and
  2788. the modified flag. The exact behavior of the
  2789. command depends on the option argument that
  2790. follows the edit argument. The following forms
  2791. of the command are currently supported:
  2792. edit_modified, edit_redo, edit_reset, edit_separator
  2793. and edit_undo
  2794. """
  2795. return self.tk.call(self._w, 'edit', *args)
  2796. def edit_modified(self, arg=None):
  2797. """Get or Set the modified flag
  2798. If arg is not specified, returns the modified
  2799. flag of the widget. The insert, delete, edit undo and
  2800. edit redo commands or the user can set or clear the
  2801. modified flag. If boolean is specified, sets the
  2802. modified flag of the widget to arg.
  2803. """
  2804. return self.edit("modified", arg)
  2805. def edit_redo(self):
  2806. """Redo the last undone edit
  2807. When the undo option is true, reapplies the last
  2808. undone edits provided no other edits were done since
  2809. then. Generates an error when the redo stack is empty.
  2810. Does nothing when the undo option is false.
  2811. """
  2812. return self.edit("redo")
  2813. def edit_reset(self):
  2814. """Clears the undo and redo stacks
  2815. """
  2816. return self.edit("reset")
  2817. def edit_separator(self):
  2818. """Inserts a separator (boundary) on the undo stack.
  2819. Does nothing when the undo option is false
  2820. """
  2821. return self.edit("separator")
  2822. def edit_undo(self):
  2823. """Undoes the last edit action
  2824. If the undo option is true. An edit action is defined
  2825. as all the insert and delete commands that are recorded
  2826. on the undo stack in between two separators. Generates
  2827. an error when the undo stack is empty. Does nothing
  2828. when the undo option is false
  2829. """
  2830. return self.edit("undo")
  2831. def get(self, index1, index2=None):
  2832. """Return the text from INDEX1 to INDEX2 (not included)."""
  2833. return self.tk.call(self._w, 'get', index1, index2)
  2834. # (Image commands are new in 8.0)
  2835. def image_cget(self, index, option):
  2836. """Return the value of OPTION of an embedded image at INDEX."""
  2837. if option[:1] != "-":
  2838. option = "-" + option
  2839. if option[-1:] == "_":
  2840. option = option[:-1]
  2841. return self.tk.call(self._w, "image", "cget", index, option)
  2842. def image_configure(self, index, cnf=None, **kw):
  2843. """Configure an embedded image at INDEX."""
  2844. return self._configure(('image', 'configure', index), cnf, kw)
  2845. def image_create(self, index, cnf={}, **kw):
  2846. """Create an embedded image at INDEX."""
  2847. return self.tk.call(
  2848. self._w, "image", "create", index,
  2849. *self._options(cnf, kw))
  2850. def image_names(self):
  2851. """Return all names of embedded images in this widget."""
  2852. return self.tk.call(self._w, "image", "names")
  2853. def index(self, index):
  2854. """Return the index in the form line.char for INDEX."""
  2855. return str(self.tk.call(self._w, 'index', index))
  2856. def insert(self, index, chars, *args):
  2857. """Insert CHARS before the characters at INDEX. An additional
  2858. tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
  2859. self.tk.call((self._w, 'insert', index, chars) + args)
  2860. def mark_gravity(self, markName, direction=None):
  2861. """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
  2862. Return the current value if None is given for DIRECTION."""
  2863. return self.tk.call(
  2864. (self._w, 'mark', 'gravity', markName, direction))
  2865. def mark_names(self):
  2866. """Return all mark names."""
  2867. return self.tk.splitlist(self.tk.call(
  2868. self._w, 'mark', 'names'))
  2869. def mark_set(self, markName, index):
  2870. """Set mark MARKNAME before the character at INDEX."""
  2871. self.tk.call(self._w, 'mark', 'set', markName, index)
  2872. def mark_unset(self, *markNames):
  2873. """Delete all marks in MARKNAMES."""
  2874. self.tk.call((self._w, 'mark', 'unset') + markNames)
  2875. def mark_next(self, index):
  2876. """Return the name of the next mark after INDEX."""
  2877. return self.tk.call(self._w, 'mark', 'next', index) or None
  2878. def mark_previous(self, index):
  2879. """Return the name of the previous mark before INDEX."""
  2880. return self.tk.call(self._w, 'mark', 'previous', index) or None
  2881. def scan_mark(self, x, y):
  2882. """Remember the current X, Y coordinates."""
  2883. self.tk.call(self._w, 'scan', 'mark', x, y)
  2884. def scan_dragto(self, x, y):
  2885. """Adjust the view of the text to 10 times the
  2886. difference between X and Y and the coordinates given in
  2887. scan_mark."""
  2888. self.tk.call(self._w, 'scan', 'dragto', x, y)
  2889. def search(self, pattern, index, stopindex=None,
  2890. forwards=None, backwards=None, exact=None,
  2891. regexp=None, nocase=None, count=None, elide=None):
  2892. """Search PATTERN beginning from INDEX until STOPINDEX.
  2893. Return the index of the first character of a match or an
  2894. empty string."""
  2895. args = [self._w, 'search']
  2896. if forwards: args.append('-forwards')
  2897. if backwards: args.append('-backwards')
  2898. if exact: args.append('-exact')
  2899. if regexp: args.append('-regexp')
  2900. if nocase: args.append('-nocase')
  2901. if elide: args.append('-elide')
  2902. if count: args.append('-count'); args.append(count)
  2903. if pattern and pattern[0] == '-': args.append('--')
  2904. args.append(pattern)
  2905. args.append(index)
  2906. if stopindex: args.append(stopindex)
  2907. return str(self.tk.call(tuple(args)))
  2908. def see(self, index):
  2909. """Scroll such that the character at INDEX is visible."""
  2910. self.tk.call(self._w, 'see', index)
  2911. def tag_add(self, tagName, index1, *args):
  2912. """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
  2913. Additional pairs of indices may follow in ARGS."""
  2914. self.tk.call(
  2915. (self._w, 'tag', 'add', tagName, index1) + args)
  2916. def tag_unbind(self, tagName, sequence, funcid=None):
  2917. """Unbind for all characters with TAGNAME for event SEQUENCE the
  2918. function identified with FUNCID."""
  2919. self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
  2920. if funcid:
  2921. self.deletecommand(funcid)
  2922. def tag_bind(self, tagName, sequence, func, add=None):
  2923. """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
  2924. An additional boolean parameter ADD specifies whether FUNC will be
  2925. called additionally to the other bound function or whether it will
  2926. replace the previous function. See bind for the return value."""
  2927. return self._bind((self._w, 'tag', 'bind', tagName),
  2928. sequence, func, add)
  2929. def tag_cget(self, tagName, option):
  2930. """Return the value of OPTION for tag TAGNAME."""
  2931. if option[:1] != '-':
  2932. option = '-' + option
  2933. if option[-1:] == '_':
  2934. option = option[:-1]
  2935. return self.tk.call(self._w, 'tag', 'cget', tagName, option)
  2936. def tag_configure(self, tagName, cnf=None, **kw):
  2937. """Configure a tag TAGNAME."""
  2938. return self._configure(('tag', 'configure', tagName), cnf, kw)
  2939. tag_config = tag_configure
  2940. def tag_delete(self, *tagNames):
  2941. """Delete all tags in TAGNAMES."""
  2942. self.tk.call((self._w, 'tag', 'delete') + tagNames)
  2943. def tag_lower(self, tagName, belowThis=None):
  2944. """Change the priority of tag TAGNAME such that it is lower
  2945. than the priority of BELOWTHIS."""
  2946. self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
  2947. def tag_names(self, index=None):
  2948. """Return a list of all tag names."""
  2949. return self.tk.splitlist(
  2950. self.tk.call(self._w, 'tag', 'names', index))
  2951. def tag_nextrange(self, tagName, index1, index2=None):
  2952. """Return a list of start and end index for the first sequence of
  2953. characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  2954. The text is searched forward from INDEX1."""
  2955. return self.tk.splitlist(self.tk.call(
  2956. self._w, 'tag', 'nextrange', tagName, index1, index2))
  2957. def tag_prevrange(self, tagName, index1, index2=None):
  2958. """Return a list of start and end index for the first sequence of
  2959. characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  2960. The text is searched backwards from INDEX1."""
  2961. return self.tk.splitlist(self.tk.call(
  2962. self._w, 'tag', 'prevrange', tagName, index1, index2))
  2963. def tag_raise(self, tagName, aboveThis=None):
  2964. """Change the priority of tag TAGNAME such that it is higher
  2965. than the priority of ABOVETHIS."""
  2966. self.tk.call(
  2967. self._w, 'tag', 'raise', tagName, aboveThis)
  2968. def tag_ranges(self, tagName):
  2969. """Return a list of ranges of text which have tag TAGNAME."""
  2970. return self.tk.splitlist(self.tk.call(
  2971. self._w, 'tag', 'ranges', tagName))
  2972. def tag_remove(self, tagName, index1, index2=None):
  2973. """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
  2974. self.tk.call(
  2975. self._w, 'tag', 'remove', tagName, index1, index2)
  2976. def window_cget(self, index, option):
  2977. """Return the value of OPTION of an embedded window at INDEX."""
  2978. if option[:1] != '-':
  2979. option = '-' + option
  2980. if option[-1:] == '_':
  2981. option = option[:-1]
  2982. return self.tk.call(self._w, 'window', 'cget', index, option)
  2983. def window_configure(self, index, cnf=None, **kw):
  2984. """Configure an embedded window at INDEX."""
  2985. return self._configure(('window', 'configure', index), cnf, kw)
  2986. window_config = window_configure
  2987. def window_create(self, index, cnf={}, **kw):
  2988. """Create a window at INDEX."""
  2989. self.tk.call(
  2990. (self._w, 'window', 'create', index)
  2991. + self._options(cnf, kw))
  2992. def window_names(self):
  2993. """Return all names of embedded windows in this widget."""
  2994. return self.tk.splitlist(
  2995. self.tk.call(self._w, 'window', 'names'))
  2996. def yview_pickplace(self, *what):
  2997. """Obsolete function, use see."""
  2998. self.tk.call((self._w, 'yview', '-pickplace') + what)
  2999. class _setit:
  3000. """Internal class. It wraps the command in the widget OptionMenu."""
  3001. def __init__(self, var, value, callback=None):
  3002. self.__value = value
  3003. self.__var = var
  3004. self.__callback = callback
  3005. def __call__(self, *args):
  3006. self.__var.set(self.__value)
  3007. if self.__callback:
  3008. self.__callback(self.__value, *args)
  3009. class OptionMenu(Menubutton):
  3010. """OptionMenu which allows the user to select a value from a menu."""
  3011. def __init__(self, master, variable, value, *values, **kwargs):
  3012. """Construct an optionmenu widget with the parent MASTER, with
  3013. the resource textvariable set to VARIABLE, the initially selected
  3014. value VALUE, the other menu values VALUES and an additional
  3015. keyword argument command."""
  3016. kw = {"borderwidth": 2, "textvariable": variable,
  3017. "indicatoron": 1, "relief": RAISED, "anchor": "c",
  3018. "highlightthickness": 2}
  3019. Widget.__init__(self, master, "menubutton", kw)
  3020. self.widgetName = 'tk_optionMenu'
  3021. menu = self.__menu = Menu(self, name="menu", tearoff=0)
  3022. self.menuname = menu._w
  3023. # 'command' is the only supported keyword
  3024. callback = kwargs.get('command')
  3025. if 'command' in kwargs:
  3026. del kwargs['command']
  3027. if kwargs:
  3028. raise TclError, 'unknown option -'+kwargs.keys()[0]
  3029. menu.add_command(label=value,
  3030. command=_setit(variable, value, callback))
  3031. for v in values:
  3032. menu.add_command(label=v,
  3033. command=_setit(variable, v, callback))
  3034. self["menu"] = menu
  3035. def __getitem__(self, name):
  3036. if name == 'menu':
  3037. return self.__menu
  3038. return Widget.__getitem__(self, name)
  3039. def destroy(self):
  3040. """Destroy this widget and the associated menu."""
  3041. Menubutton.destroy(self)
  3042. self.__menu = None
  3043. class Image:
  3044. """Base class for images."""
  3045. _last_id = 0
  3046. def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
  3047. self.name = None
  3048. if not master:
  3049. master = _default_root
  3050. if not master:
  3051. raise RuntimeError, 'Too early to create image'
  3052. self.tk = getattr(master, 'tk', master)
  3053. if not name:
  3054. Image._last_id += 1
  3055. name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
  3056. # The following is needed for systems where id(x)
  3057. # can return a negative number, such as Linux/m68k:
  3058. if name[0] == '-': name = '_' + name[1:]
  3059. if kw and cnf: cnf = _cnfmerge((cnf, kw))
  3060. elif kw: cnf = kw
  3061. options = ()
  3062. for k, v in cnf.items():
  3063. if hasattr(v, '__call__'):
  3064. v = self._register(v)
  3065. elif k in ('data', 'maskdata'):
  3066. v = self.tk._createbytearray(v)
  3067. options = options + ('-'+k, v)
  3068. self.tk.call(('image', 'create', imgtype, name,) + options)
  3069. self.name = name
  3070. def __str__(self): return self.name
  3071. def __del__(self):
  3072. if self.name:
  3073. try:
  3074. self.tk.call('image', 'delete', self.name)
  3075. except TclError:
  3076. # May happen if the root was destroyed
  3077. pass
  3078. def __setitem__(self, key, value):
  3079. self.tk.call(self.name, 'configure', '-'+key, value)
  3080. def __getitem__(self, key):
  3081. return self.tk.call(self.name, 'configure', '-'+key)
  3082. def configure(self, **kw):
  3083. """Configure the image."""
  3084. res = ()
  3085. for k, v in _cnfmerge(kw).items():
  3086. if v is not None:
  3087. if k[-1] == '_': k = k[:-1]
  3088. if hasattr(v, '__call__'):
  3089. v = self._register(v)
  3090. elif k in ('data', 'maskdata'):
  3091. v = self.tk._createbytearray(v)
  3092. res = res + ('-'+k, v)
  3093. self.tk.call((self.name, 'config') + res)
  3094. config = configure
  3095. def height(self):
  3096. """Return the height of the image."""
  3097. return getint(
  3098. self.tk.call('image', 'height', self.name))
  3099. def type(self):
  3100. """Return the type of the imgage, e.g. "photo" or "bitmap"."""
  3101. return self.tk.call('image', 'type', self.name)
  3102. def width(self):
  3103. """Return the width of the image."""
  3104. return getint(
  3105. self.tk.call('image', 'width', self.name))
  3106. class PhotoImage(Image):
  3107. """Widget which can display colored images in GIF, PPM/PGM format."""
  3108. def __init__(self, name=None, cnf={}, master=None, **kw):
  3109. """Create an image with NAME.
  3110. Valid resource names: data, format, file, gamma, height, palette,
  3111. width."""
  3112. Image.__init__(self, 'photo', name, cnf, master, **kw)
  3113. def blank(self):
  3114. """Display a transparent image."""
  3115. self.tk.call(self.name, 'blank')
  3116. def cget(self, option):
  3117. """Return the value of OPTION."""
  3118. return self.tk.call(self.name, 'cget', '-' + option)
  3119. # XXX config
  3120. def __getitem__(self, key):
  3121. return self.tk.call(self.name, 'cget', '-' + key)
  3122. # XXX copy -from, -to, ...?
  3123. def copy(self):
  3124. """Return a new PhotoImage with the same image as this widget."""
  3125. destImage = PhotoImage(master=self.tk)
  3126. self.tk.call(destImage, 'copy', self.name)
  3127. return destImage
  3128. def zoom(self, x, y=''):
  3129. """Return a new PhotoImage with the same image as this widget
  3130. but zoom it with a factor of x in the X direction and y in the Y
  3131. direction. If y is not given, the default value is the same as x.
  3132. """
  3133. destImage = PhotoImage(master=self.tk)
  3134. if y=='': y=x
  3135. self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
  3136. return destImage
  3137. def subsample(self, x, y=''):
  3138. """Return a new PhotoImage based on the same image as this widget
  3139. but use only every Xth or Yth pixel. If y is not given, the
  3140. default value is the same as x.
  3141. """
  3142. destImage = PhotoImage(master=self.tk)
  3143. if y=='': y=x
  3144. self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
  3145. return destImage
  3146. def get(self, x, y):
  3147. """Return the color (red, green, blue) of the pixel at X,Y."""
  3148. return self.tk.call(self.name, 'get', x, y)
  3149. def put(self, data, to=None):
  3150. """Put row formatted colors to image starting from
  3151. position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
  3152. args = (self.name, 'put', data)
  3153. if to:
  3154. if to[0] == '-to':
  3155. to = to[1:]
  3156. args = args + ('-to',) + tuple(to)
  3157. self.tk.call(args)
  3158. # XXX read
  3159. def write(self, filename, format=None, from_coords=None):
  3160. """Write image to file FILENAME in FORMAT starting from
  3161. position FROM_COORDS."""
  3162. args = (self.name, 'write', filename)
  3163. if format:
  3164. args = args + ('-format', format)
  3165. if from_coords:
  3166. args = args + ('-from',) + tuple(from_coords)
  3167. self.tk.call(args)
  3168. class BitmapImage(Image):
  3169. """Widget which can display a bitmap."""
  3170. def __init__(self, name=None, cnf={}, master=None, **kw):
  3171. """Create a bitmap with NAME.
  3172. Valid resource names: background, data, file, foreground, maskdata, maskfile."""
  3173. Image.__init__(self, 'bitmap', name, cnf, master, **kw)
  3174. def image_names():
  3175. return _default_root.tk.splitlist(_default_root.tk.call('image', 'names'))
  3176. def image_types():
  3177. return _default_root.tk.splitlist(_default_root.tk.call('image', 'types'))
  3178. class Spinbox(Widget, XView):
  3179. """spinbox widget."""
  3180. def __init__(self, master=None, cnf={}, **kw):
  3181. """Construct a spinbox widget with the parent MASTER.
  3182. STANDARD OPTIONS
  3183. activebackground, background, borderwidth,
  3184. cursor, exportselection, font, foreground,
  3185. highlightbackground, highlightcolor,
  3186. highlightthickness, insertbackground,
  3187. insertborderwidth, insertofftime,
  3188. insertontime, insertwidth, justify, relief,
  3189. repeatdelay, repeatinterval,
  3190. selectbackground, selectborderwidth
  3191. selectforeground, takefocus, textvariable
  3192. xscrollcommand.
  3193. WIDGET-SPECIFIC OPTIONS
  3194. buttonbackground, buttoncursor,
  3195. buttondownrelief, buttonuprelief,
  3196. command, disabledbackground,
  3197. disabledforeground, format, from,
  3198. invalidcommand, increment,
  3199. readonlybackground, state, to,
  3200. validate, validatecommand values,
  3201. width, wrap,
  3202. """
  3203. Widget.__init__(self, master, 'spinbox', cnf, kw)
  3204. def bbox(self, index):
  3205. """Return a tuple of X1,Y1,X2,Y2 coordinates for a
  3206. rectangle which encloses the character given by index.
  3207. The first two elements of the list give the x and y
  3208. coordinates of the upper-left corner of the screen
  3209. area covered by the character (in pixels relative
  3210. to the widget) and the last two elements give the
  3211. width and height of the character, in pixels. The
  3212. bounding box may refer to a region outside the
  3213. visible area of the window.
  3214. """
  3215. return self._getints(self.tk.call(self._w, 'bbox', index)) or None
  3216. def delete(self, first, last=None):
  3217. """Delete one or more elements of the spinbox.
  3218. First is the index of the first character to delete,
  3219. and last is the index of the character just after
  3220. the last one to delete. If last isn't specified it
  3221. defaults to first+1, i.e. a single character is
  3222. deleted. This command returns an empty string.
  3223. """
  3224. return self.tk.call(self._w, 'delete', first, last)
  3225. def get(self):
  3226. """Returns the spinbox's string"""
  3227. return self.tk.call(self._w, 'get')
  3228. def icursor(self, index):
  3229. """Alter the position of the insertion cursor.
  3230. The insertion cursor will be displayed just before
  3231. the character given by index. Returns an empty string
  3232. """
  3233. return self.tk.call(self._w, 'icursor', index)
  3234. def identify(self, x, y):
  3235. """Returns the name of the widget at position x, y
  3236. Return value is one of: none, buttondown, buttonup, entry
  3237. """
  3238. return self.tk.call(self._w, 'identify', x, y)
  3239. def index(self, index):
  3240. """Returns the numerical index corresponding to index
  3241. """
  3242. return self.tk.call(self._w, 'index', index)
  3243. def insert(self, index, s):
  3244. """Insert string s at index
  3245. Returns an empty string.
  3246. """
  3247. return self.tk.call(self._w, 'insert', index, s)
  3248. def invoke(self, element):
  3249. """Causes the specified element to be invoked
  3250. The element could be buttondown or buttonup
  3251. triggering the action associated with it.
  3252. """
  3253. return self.tk.call(self._w, 'invoke', element)
  3254. def scan(self, *args):
  3255. """Internal function."""
  3256. return self._getints(
  3257. self.tk.call((self._w, 'scan') + args)) or ()
  3258. def scan_mark(self, x):
  3259. """Records x and the current view in the spinbox window;
  3260. used in conjunction with later scan dragto commands.
  3261. Typically this command is associated with a mouse button
  3262. press in the widget. It returns an empty string.
  3263. """
  3264. return self.scan("mark", x)
  3265. def scan_dragto(self, x):
  3266. """Compute the difference between the given x argument
  3267. and the x argument to the last scan mark command
  3268. It then adjusts the view left or right by 10 times the
  3269. difference in x-coordinates. This command is typically
  3270. associated with mouse motion events in the widget, to
  3271. produce the effect of dragging the spinbox at high speed
  3272. through the window. The return value is an empty string.
  3273. """
  3274. return self.scan("dragto", x)
  3275. def selection(self, *args):
  3276. """Internal function."""
  3277. return self._getints(
  3278. self.tk.call((self._w, 'selection') + args)) or ()
  3279. def selection_adjust(self, index):
  3280. """Locate the end of the selection nearest to the character
  3281. given by index,
  3282. Then adjust that end of the selection to be at index
  3283. (i.e including but not going beyond index). The other
  3284. end of the selection is made the anchor point for future
  3285. select to commands. If the selection isn't currently in
  3286. the spinbox, then a new selection is created to include
  3287. the characters between index and the most recent selection
  3288. anchor point, inclusive. Returns an empty string.
  3289. """
  3290. return self.selection("adjust", index)
  3291. def selection_clear(self):
  3292. """Clear the selection
  3293. If the selection isn't in this widget then the
  3294. command has no effect. Returns an empty string.
  3295. """
  3296. return self.selection("clear")
  3297. def selection_element(self, element=None):
  3298. """Sets or gets the currently selected element.
  3299. If a spinbutton element is specified, it will be
  3300. displayed depressed
  3301. """
  3302. return self.selection("element", element)
  3303. ###########################################################################
  3304. class LabelFrame(Widget):
  3305. """labelframe widget."""
  3306. def __init__(self, master=None, cnf={}, **kw):
  3307. """Construct a labelframe widget with the parent MASTER.
  3308. STANDARD OPTIONS
  3309. borderwidth, cursor, font, foreground,
  3310. highlightbackground, highlightcolor,
  3311. highlightthickness, padx, pady, relief,
  3312. takefocus, text
  3313. WIDGET-SPECIFIC OPTIONS
  3314. background, class, colormap, container,
  3315. height, labelanchor, labelwidget,
  3316. visual, width
  3317. """
  3318. Widget.__init__(self, master, 'labelframe', cnf, kw)
  3319. ########################################################################
  3320. class PanedWindow(Widget):
  3321. """panedwindow widget."""
  3322. def __init__(self, master=None, cnf={}, **kw):
  3323. """Construct a panedwindow widget with the parent MASTER.
  3324. STANDARD OPTIONS
  3325. background, borderwidth, cursor, height,
  3326. orient, relief, width
  3327. WIDGET-SPECIFIC OPTIONS
  3328. handlepad, handlesize, opaqueresize,
  3329. sashcursor, sashpad, sashrelief,
  3330. sashwidth, showhandle,
  3331. """
  3332. Widget.__init__(self, master, 'panedwindow', cnf, kw)
  3333. def add(self, child, **kw):
  3334. """Add a child widget to the panedwindow in a new pane.
  3335. The child argument is the name of the child widget
  3336. followed by pairs of arguments that specify how to
  3337. manage the windows. The possible options and values
  3338. are the ones accepted by the paneconfigure method.
  3339. """
  3340. self.tk.call((self._w, 'add', child) + self._options(kw))
  3341. def remove(self, child):
  3342. """Remove the pane containing child from the panedwindow
  3343. All geometry management options for child will be forgotten.
  3344. """
  3345. self.tk.call(self._w, 'forget', child)
  3346. forget=remove
  3347. def identify(self, x, y):
  3348. """Identify the panedwindow component at point x, y
  3349. If the point is over a sash or a sash handle, the result
  3350. is a two element list containing the index of the sash or
  3351. handle, and a word indicating whether it is over a sash
  3352. or a handle, such as {0 sash} or {2 handle}. If the point
  3353. is over any other part of the panedwindow, the result is
  3354. an empty list.
  3355. """
  3356. return self.tk.call(self._w, 'identify', x, y)
  3357. def proxy(self, *args):
  3358. """Internal function."""
  3359. return self._getints(
  3360. self.tk.call((self._w, 'proxy') + args)) or ()
  3361. def proxy_coord(self):
  3362. """Return the x and y pair of the most recent proxy location
  3363. """
  3364. return self.proxy("coord")
  3365. def proxy_forget(self):
  3366. """Remove the proxy from the display.
  3367. """
  3368. return self.proxy("forget")
  3369. def proxy_place(self, x, y):
  3370. """Place the proxy at the given x and y coordinates.
  3371. """
  3372. return self.proxy("place", x, y)
  3373. def sash(self, *args):
  3374. """Internal function."""
  3375. return self._getints(
  3376. self.tk.call((self._w, 'sash') + args)) or ()
  3377. def sash_coord(self, index):
  3378. """Return the current x and y pair for the sash given by index.
  3379. Index must be an integer between 0 and 1 less than the
  3380. number of panes in the panedwindow. The coordinates given are
  3381. those of the top left corner of the region containing the sash.
  3382. pathName sash dragto index x y This command computes the
  3383. difference between the given coordinates and the coordinates
  3384. given to the last sash coord command for the given sash. It then
  3385. moves that sash the computed difference. The return value is the
  3386. empty string.
  3387. """
  3388. return self.sash("coord", index)
  3389. def sash_mark(self, index):
  3390. """Records x and y for the sash given by index;
  3391. Used in conjunction with later dragto commands to move the sash.
  3392. """
  3393. return self.sash("mark", index)
  3394. def sash_place(self, index, x, y):
  3395. """Place the sash given by index at the given coordinates
  3396. """
  3397. return self.sash("place", index, x, y)
  3398. def panecget(self, child, option):
  3399. """Query a management option for window.
  3400. Option may be any value allowed by the paneconfigure subcommand
  3401. """
  3402. return self.tk.call(
  3403. (self._w, 'panecget') + (child, '-'+option))
  3404. def paneconfigure(self, tagOrId, cnf=None, **kw):
  3405. """Query or modify the management options for window.
  3406. If no option is specified, returns a list describing all
  3407. of the available options for pathName. If option is
  3408. specified with no value, then the command returns a list
  3409. describing the one named option (this list will be identical
  3410. to the corresponding sublist of the value returned if no
  3411. option is specified). If one or more option-value pairs are
  3412. specified, then the command modifies the given widget
  3413. option(s) to have the given value(s); in this case the
  3414. command returns an empty string. The following options
  3415. are supported:
  3416. after window
  3417. Insert the window after the window specified. window
  3418. should be the name of a window already managed by pathName.
  3419. before window
  3420. Insert the window before the window specified. window
  3421. should be the name of a window already managed by pathName.
  3422. height size
  3423. Specify a height for the window. The height will be the
  3424. outer dimension of the window including its border, if
  3425. any. If size is an empty string, or if -height is not
  3426. specified, then the height requested internally by the
  3427. window will be used initially; the height may later be
  3428. adjusted by the movement of sashes in the panedwindow.
  3429. Size may be any value accepted by Tk_GetPixels.
  3430. minsize n
  3431. Specifies that the size of the window cannot be made
  3432. less than n. This constraint only affects the size of
  3433. the widget in the paned dimension -- the x dimension
  3434. for horizontal panedwindows, the y dimension for
  3435. vertical panedwindows. May be any value accepted by
  3436. Tk_GetPixels.
  3437. padx n
  3438. Specifies a non-negative value indicating how much
  3439. extra space to leave on each side of the window in
  3440. the X-direction. The value may have any of the forms
  3441. accepted by Tk_GetPixels.
  3442. pady n
  3443. Specifies a non-negative value indicating how much
  3444. extra space to leave on each side of the window in
  3445. the Y-direction. The value may have any of the forms
  3446. accepted by Tk_GetPixels.
  3447. sticky style
  3448. If a window's pane is larger than the requested
  3449. dimensions of the window, this option may be used
  3450. to position (or stretch) the window within its pane.
  3451. Style is a string that contains zero or more of the
  3452. characters n, s, e or w. The string can optionally
  3453. contains spaces or commas, but they are ignored. Each
  3454. letter refers to a side (north, south, east, or west)
  3455. that the window will "stick" to. If both n and s
  3456. (or e and w) are specified, the window will be
  3457. stretched to fill the entire height (or width) of
  3458. its cavity.
  3459. width size
  3460. Specify a width for the window. The width will be
  3461. the outer dimension of the window including its
  3462. border, if any. If size is an empty string, or
  3463. if -width is not specified, then the width requested
  3464. internally by the window will be used initially; the
  3465. width may later be adjusted by the movement of sashes
  3466. in the panedwindow. Size may be any value accepted by
  3467. Tk_GetPixels.
  3468. """
  3469. if cnf is None and not kw:
  3470. return self._getconfigure(self._w, 'paneconfigure', tagOrId)
  3471. if type(cnf) == StringType and not kw:
  3472. return self._getconfigure1(
  3473. self._w, 'paneconfigure', tagOrId, '-'+cnf)
  3474. self.tk.call((self._w, 'paneconfigure', tagOrId) +
  3475. self._options(cnf, kw))
  3476. paneconfig = paneconfigure
  3477. def panes(self):
  3478. """Returns an ordered list of the child panes."""
  3479. return self.tk.splitlist(self.tk.call(self._w, 'panes'))
  3480. ######################################################################
  3481. # Extensions:
  3482. class Studbutton(Button):
  3483. def __init__(self, master=None, cnf={}, **kw):
  3484. Widget.__init__(self, master, 'studbutton', cnf, kw)
  3485. self.bind('<Any-Enter>', self.tkButtonEnter)
  3486. self.bind('<Any-Leave>', self.tkButtonLeave)
  3487. self.bind('<1>', self.tkButtonDown)
  3488. self.bind('<ButtonRelease-1>', self.tkButtonUp)
  3489. class Tributton(Button):
  3490. def __init__(self, master=None, cnf={}, **kw):
  3491. Widget.__init__(self, master, 'tributton', cnf, kw)
  3492. self.bind('<Any-Enter>', self.tkButtonEnter)
  3493. self.bind('<Any-Leave>', self.tkButtonLeave)
  3494. self.bind('<1>', self.tkButtonDown)
  3495. self.bind('<ButtonRelease-1>', self.tkButtonUp)
  3496. self['fg'] = self['bg']
  3497. self['activebackground'] = self['bg']
  3498. ######################################################################
  3499. # Test:
  3500. def _test():
  3501. root = Tk()
  3502. text = "This is Tcl/Tk version %s" % TclVersion
  3503. if TclVersion >= 8.1:
  3504. try:
  3505. text = text + unicode("\nThis should be a cedilla: \347",
  3506. "iso-8859-1")
  3507. except NameError:
  3508. pass # no unicode support
  3509. label = Label(root, text=text)
  3510. label.pack()
  3511. test = Button(root, text="Click me!",
  3512. command=lambda root=root: root.test.configure(
  3513. text="[%s]" % root.test['text']))
  3514. test.pack()
  3515. root.test = test
  3516. quit = Button(root, text="QUIT", command=root.destroy)
  3517. quit.pack()
  3518. # The following three commands are needed so the window pops
  3519. # up on top on Windows...
  3520. root.iconify()
  3521. root.update()
  3522. root.deiconify()
  3523. root.mainloop()
  3524. if __name__ == '__main__':
  3525. _test()