__init__.py 168 KB

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