__init__.py 163 KB

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