Tkinter Toolbox Reference 2021D 040821

? 2021 John A. Oakey V

JR2021D 1

TOOLBOX

For 3.6+

tkinter 2021 Toolbox Reference Section 1: tkinter without Ttk

A Practical Outline of the Process Note: in this doc ument the symbol means "returns" or "yields".

of Creating a tkinter Application

(This creates a minimal environment for an actual application - some steps may differ depending on the needs or complexity of your design.)

Import : f rom tkinter import * or import tkinter as tk requires using "tk." prefix to c ommands )

Define any variables needed to establis h root Establish root : root=Tk() or root=tk.TK() a special singular

widget which must be c reated to initialize tkinter (from now on in this doc , import * is assumed - no 'tk.' element needed) then ** Def ine root geometry and option values Define any variables needed for a Toplevel widget Create a Toplev el widget ? a window in whic h to build your app; you c an have more than one Create Functi on s an d establish Variabl es - Functions c an be callback widgets invoked to res pond to events; comma nds and lambda statements can serve to res pond as well Create Widget s: widge t_name = widge t_type (parent

[,attribute values] [,options] [,a bound callback]) Bind additional or non-inherent events Apply Geomet ry Pla cement: with grid, place or pack "root .mainloop()" - "blocks", i.e., defines end of the program

Options, Values, Processes

Colors: c an be given as names or as hex definitions : #rgb, #rrggbb, # rrrgggbbb, #rrrrggggbbbb; (see ) Control Varia bles - global, update automatically; constructors : =DoubleVar(), =IntVar(), =BooleanVa r(), =StringVar, ; use: v_name.set(value)and v_name.get(value) Cursors: many available suc h as : "arrow" "circle" "clock" "cross" "dotbox" "exc hange" "fleur" "heart" "man" "mouse" "pirate" "plus" "s huttle" "sizing" "spider" "spraycan" "star" "trek" "watc h" Distance: (1 ) pixels numeric ; (2 ) absolute dis tances s trings with a trailing c haracter denoting units : c-centimeters , i-inc hes , mmillimeters , p-printer's points - these vary by font Fonts: A list or tuple s pecifying name, s ize, weight. E x: font= ("Verdana", 10 , "bold"). Font sizes with positive numbers measured in points; negative numbered sizes are meas ured in pixels. Images: B&W id constructor: myBWpic = tk.BitmapI mage (file=myimagefile.xbm); Color myphotoimage = PhotoImage (file=myimagefile. {.gif, .pgm, .ppm formats }) see pg 7 Just if y: "left", "center", "right", "fill" include the quotes Region: 4 s pace-delimited dis tances "3i 2i 4.5i 2i" Relief : "raised", "s unken", "flat", "groove", "ridge"

Wrap: "none", "char", or "word" - for example: text box attribute

WIDGETS Checkbu on

Entry

B ut to n

F ra me

C anvas

La be l

LabelFrame Message Sc rollbar

Lis tbox

PanedWindow Spinbox

M e nu

Radiobutton Text

Menubutton Scale

T o ple ve l

Creating WIDGETS C reate a widget by naming it and setting it

equal to a type (s ee above) then setting it's attributes and options . The first attribute set must be it's parent window. O ptions can als o be set using the configure method, i.e., widg.config(bg="snow" ). A primary c allback is bound with command=function/method/lambda

# A Basic "Boilerplate"

Header for Small Apps

# by John O akey for # get the module, like any other Python module f rom tkinter import * # establis h root (set variables if needed) root = Tk() root.attributes('-fullscreen', T rue) #set full screen root.c onfigure(background='SteelBlue4') # c onfigure root options root.attributes("-alpha", 0 .5 ) # and attributes (opacity in this case)

# get info on sc reen s ize: showing the math here scrW, sc rH = root.winfo_screenwidth(),\

root.winfo_sc reenheight() # build a s tring variable telling tkinter how to # c reate and position our T oplevel window workwindow = s tr(1024) + "x" + s tr(768)+ "+" +s tr(int((sc rW-1024)/2)) + "+" +str(int((scrH768)/2 )) # c reate the Toplevel under the root parent, set its geometry and title top1 = Toplevel(root, bg=" light blue" ) top1 .geometry(workwindow) top1 .title("Top 1 - Workwindow")

# prepare for s lightly more c omplex apps top1 .attributes("-topmos t", 1 ) # make s ure top1 is on top to s tart root.update() # but don't leave it locked in place top1 .attributes("-topmos t", 0 ) # in case you need to use 'lower' or 'lift'

#exit button - note: this example uses grid geometry manager b0 =Button(root, text="Egress",\ command=root.des troy) b0 .grid(row=0 ,column=0 ,ipadx=10 , ipady=10 , pady=5 , padx=5 , sticky = W+N )

# c reate any functions and global variables that widgets and processes will need my_text = S tringV ar() my_text.set("Hello World!")

# ____________________________

# c reate the rest of your program here l1 =Label(top1 , bg="snow", text=my_text.get(), font=('Times New Roman',14 ,'bold')) l1 .grid(row=1 ,column=1 ,ipadx=20 , ipady=20 , pady=50 , padx=50 )

# ____________________________

# and finally, tell tkinter it may begin execution root.mainloop() # but s top right here

Inherent class bindings are defined for all widgets giving them default callback behaviors to certain events--when a bound event occurs , bindings execute your method, lambda expression, or f unction s pec ified at the widget's c reation, or "secondarily" added later with the .bind method.

A widge t crea tion and binding syntax diagram : b1 will have a line n background color and read "Push!", if clicked it r uns the callback Your widget nam e option s (ex: background color) function to bind when an auto event occurs

b1=Button(parent, bg= `linen', text= `Push!', command= my_callback_function)

wi dget type parent window name options (ex: label text) *button click binding is automatic

? 2021 John A. Oakey V

JR2021D 2

TOOLBOX tkinter 0221 Toolbox Reference

For 3.6+

Binding Responses When an Event (an

Common Event s

Mou se Butt on event s:

Effects an Object activity or change in state)

always in quotes like "" or

Mouse button or Keyboard are by far the mos t common types of events (see right)

but other types include crossing, f ocus, exposure, conf iguration, colormap a nd:

class: .bi nd_class()

ex: self.bind_class(w_type, "", function) and

application: .bi nd_all('', function) ex: self. bind_all('',

se l f.__p ri ntScree n)

Names given to event

" + angle bracket enc losure: like ""

or or moving with held down mouse enters widget

sequences are strings of one

Keyboa rd ev ent s:

one or more event patterns . In the widget definition (s ee "< [opt modifier(s)] type [opt detail] >"

or keyboard focus in/out of widget

page 1 ), "command =" sets the callback response. Events (like a button click)

Alt, Control, Double, like Enter like 1 , 2 , 3

Lock, Shift, T riple

or Return

can bind at 4 levels : Class, Application, Toplevel, and

"< A lt

Button

1 >"

Ins tance (the most c ommon). M any widgets have predefined or "inherent" events

whic h will automatically call any "command=" statement in their definition.

No event information is passed back for inherent c allbac ks.

Secondary Bindings: Bindings , or bindings where event environmental objects mus t

pass back, can be set with the .bind method: widget.bind ("", callba ck,

add=None/"+") T his method c onnec ts the exis ting widget to an event, a callback

Inf ormation passed back from a .bind method c allback event: widget: tkinter instance; num: button number; x,y: mouse position; x_root, y_root: mouse pos relative to

ac tion, and s pec fies if this binding s upersedes others or is executed in addition to others . ex:

l2 .bind("", my_callback_func , add='+')T he '+' allows multiple callbacks to execute. T his type of binding also will "pass

toplevel; char: character code (as a back" environmental and activity information

str); keysym: key symbol; keycode: (see left insert). An additional binding can use an

key code; other: width, height - new existing callback by defining the function with widget size (pixels); type: event type; *args in the parens : def c allback(event,* args )

"Enter" key : w.bind("", callback) any keypress; or frame. Bind (" x" , callback) where "x" is the x key Note* You may need to use w.focus_set() to activate. Special key bindi ngs ea ch encased i n "< >"; ex: ""; Cancel (the Break key), BackSpace, Tab, Shift_L (any Shift key), C ontrol_L (any Control key), A lt_L (any Alt key), Pause, Caps _Lock, Escape, Prior (Page Up), Next (Page Down), E nd, Home, Left, U p, Right, Down, P rint, I nsert, Delete, F1 , F2 , F3 , F4 , F5 , F6 , F7 , F8 , F9 , F10 , F11 , F12 , Num_Lock, and Scroll_Lock

tkinter Geometries -

ActiveState ? owns and

maintains

How Objects are Placed tkinter

Sugge sted reading: https :// resources /quic k-reads /how-to-pos ition-widgets- in-tkinter/

Using lambda to pass simple values i n a bi ndi ng O rdinarily no variables are passed in an automatic binding and only event data in manual bindings . A lambda statement can be used to overcome this limitation with simple data - for example regular or control variables . Auto binding examples: command= lambda: button1callback(myvar) -or-

O nce a widget (or any objec t) is c reated, tkinter uses one of command= lambda: button1callback(cvar.get())

three geometries to arrange, register and place them on a the callback function must s pecify a receiving variable

screen. Never mix these systems in the same master window! container. For a secondary bind: w.bind("", Each geometry has a number of options - see list on page 3 . lambda event, arg=variable: c allback(event, arg))

callback has 2 variables such as (event, myvar) pack: very s imple to learn and use--ideal for a new us er to

experiment with widgets and attributes but not practical for

most applications because it dec ides on all exac t placements with the programmer specifying only the relative pos itions .

grid: the generally most useful of the geometries , grid assumes placement of widgets is done in c olumns and rows and

so allows neat, though restric tive, layouts to be composed fairly easily. (I t makes Microsoft E xcel an excellent layout

planning tool.) G rid automatically sizes the grid based on the size attributes of the widgets to be positioned.

place: allows precise absolute placement using x,y c oordinates or s izing relative to another widget.

Methods: Universal Geometry Methods

grid:

[x=widget. Geometry_method()] ex: b1 .pack_forget() w.grid_bbox(column=None, row=None, x_forget() remove from manage r but do not destroy, can reuse; ex: lab1.grid_forget(), re trie ve col2=None, row2=None)

by repeating the original grid command

w.grid_size() tuple with number of c olumns and rows

x_info() a dictionary of options w.grid_info() master.grid_location(x,y) r/c tuple with indexes

x_slaves() list of sub widge ts as tk inte r widge t w.grid_remove() removes widge t from manage r;

re fe rence s. same as x_content() x_configure(options) same as .pack()

Geometry Specific Methods

but the widge t is available for re use . To change the following, you must call these on a widge t's parent: grid_columnconfigure(index , options)

place: has no other Methods.

grid_rowconfigure(index , options)

pack and grid: x_propagate(windo w_name, T/F) ; True/False; enables resizing of child widge ts if too small

index = column numbe r options: m insize =, pad=, we ight=, uniform =

comments and suggestions appreciated:

oakey.john@

? 2021 John A. Oakey

JR2021D 3

TOOLBOX tkinter 0221 Toolbox Reference

For 3.5

Geometries: Pack, Place, Grid: widget placement & formatting commands Options and Attributes

Geomet ry Opt ions

a er anchor before (other) bordermode column columnspan expand fill

Def ault or Pack Grid Place Require ment

Opt ions

other window

center

compass points

other window

inside

0

outside / ignore i nte ge r

1 FA LSE

i nte ge r true/false: 0 /1

" no ne"

"x" , "y" , " both"

Not e

name of another window default is NW name of another window border influence on slave placement column number; columns start with 0 number of columns spanned assign more s pace, distribute among widgets take up entire space, may need expand=

height in_= (target)

size n/a

distance widget name

outer dimension of window plus border pack ins ide the target widget

ipadx

0

distance

internal padding pixels /distance; horizontal

ipady

0

distance

internal padding pixels /distance; vertical

padx pady

0

0

distance distance

external padding pixels/dis tance; horizontal external padding pixels/dis tance; vertical

relheight relwidth relx

fp fp fp % * 100

fp 0 to 1 .0

height relative to master; modified by - height

fp 0 to 1 .0

width relative to master; modified by - width

0 .0 (left)- 1 .0(right) anchor point x c oordinates in mas ter window

rely

fp % * 100 0 .0 (left)- 1 .0(right) anchor point y c oordinates in mas ter window

row

firs t empty row number

row number; rows s tart with 0

rowspan

1

i nte ge r

number of rows s panned

side

s cky (glue widget to cell border)

top / ce nt ered

left/ right/ bottom to pack against W+E stretch horiz; W+E +N +S - fill all; use a

compass points string="wens" or constants =W+E +N +S

width

size

distance

outer dimension of window plus border

x

0

distance

anchor point x c oordinate in master window

y

0

distance

anchor point y c oordinate in master window

Information Methods rootx(): left edge x coordinate relative to screen

(wi nf o_x()) rooty(): left edge y coordinate relative to screen

ex: print (t op1.winf o_childre n()) list of child objects screen(): screen name as dec int; ":0.0" in Windows

atom(name (a string),displayof=0): unique int mapped to str screencells(): # of color cells

atomname(id, displayof=0): text name mapped to id

screendepth(): deffault bit depth

cells(): # of cells in colormap, a decimal string

screenheight(): height of widget screen

children(): list of child ren in stacking order, not toplevels class(): widget class colormapfull(): 1, if full

screenmmheight(): screen height in mm screenmmwidth(): screen width in mm screenvisual(): "psuedocolor" or "truecolor"

containing(window rootx, rooty, displayof=0):widget @ this pos screenwidth(: width of screen in pixels

depth(): bit depth, pixels at this

server(): widget screen xserver window info

exists(): true if widget exists

toplevel(): widget root

fpixels() window, number : fp-# of screen pixels

viewable(): True if widget chain is mapped

geometry(: geometry sting in pixels height(): widget height in pixels id(): window identifier interps(displayof=0 window): TCL interpreter mem list ismapped(): boolean; check if window created manager(): geo mgr: grid,pack,place, or class command if wid name(): widget name parent(): widget parents full name pathname(displayof=0 window) : full name of id # window pixels(): window,number : convert to pixels

visual(): directcolo r, grayscale, pseudocolor, staticcolor, staticgray, or truecolor visualid(): X identifier for visual this widget visualsavailable() : list of all visuals available for widget screen vrootheight(): hght of the virtual root window for widget vrootwidth(): width of the virtual root window for widget vrootx():x offset of virtual root rel to root window of wid screen vrooty(): y offset of virtual root rel to root window of wid scrn width(): widget width, pixels (update_idletasks) x() and y(): upper corner coord inates

pointerx(): x coord of pointer on the root pointerxy(): xy coords of pointer on the root pointery(): window y coord of pointer on the root reqheight(): min size to display widget

Const ant s Boolean: 0 /'no', 1 /'yes ' A nchor points: 'n', 'ne',

'e','se','s','s w','w','nw','center' Bit maps: 'error','gray75', 'gray50', 'gray25', 'gray12', 'hourglass', 'info', 'questhead', 'question', 'warning'

reqwidth(): min size needed to display widget

rgb(color, ): color: an RGB 3 tuple - 0 to 65535

? 2021 John A. Oakey

JR2021D 4

TOOLBOX tkinter 0221 Toolbox Reference

For 3.5

Bu tto n C an vas Che ck button E ntry Fr ame La bel La belF rame Li stbox Me nu Me nubutton Me ssage PanedW indow Ra diobutton Sca le Scr oll bar S pin bo x T ext T opl evel

Widget Options and Attributes

Def aul t Value Type

Value

Note

activebackgro und

ll

l

ll

ll ll

color

a s ystem value m ouse over or b1 press

activebor derw idth

l

dis tance value

1

m enu; on ly if displaying > 1 element

activefo regro und

ll

l

ll

l

color

a s ystem value

activere lief

l

relief

raised

displayed when element active

activestyle anc h or

aspect

ll

l

l

ll l

l

dot box, none, underline u nderline compass points, cen ter usually center

positive integer aspect

ratio

150

m essage;

auto separato rs

l boolean

TRUE, 1

text; applies only if undo is true

background or -bg l l l l l l l l l l l l l l l l l color

system

big incremen t

l

fp

0.1

large m ovement am oount

bitmap

ll

l

l

l

"" or f ilename

see predefined list see native available: " ques tion"

blo ckcurso r

l boolean

false

text;

borderwidth or -bd l l l l l l l l l l l l l l l l l l dis tance value

2 pixels

butto nbackgro und

l

color

SystemButtonFace spinbox;

butto ncurso r

l

cusor nam e

default cursor

spinbox ;

butto ndo wnr elief

l

relief

raised

spinbox ;

butto nuprelief

l

relief

raised

spinbox ;

class

ll

class f or window l determ ines options

w class name -> toplevel, frame, labelframe

clo se eno ugh

l

fp value

1.0

how close is inside

co lor map

ll

l new' or other windo w screen default

toplevel, frame, labelframe;

co mmand

ll

ll ll

callback function n am e none

co mpound

ll

l

l

l

bottom , top, left, right,

center

none

controls the display of text and images at same time

co nfine

l

boolean

True

canvas; T confin es view to scroll regio n

co ntainer

l

l boolean

false

toplevel, frame, labelframe; to em bed app

cu rs or

l l l l l l l l l l l l l l l l l l cursor name

system

see curs or options

def au lt

l

normal, active, disa bled disabled

button; disabled may draw sm aller button

dig its

l

integer

0

scale; string resolution, 0 yeilds all po sitions

direction

above, below, left, right,

l

flush

belo w

m enubutton; where m en u p ops up

disabled backg rou n d

l

l

color

system

spinbox, entry;

disabledforeground l l l l l l l

l

l

color

S ystemDisabledText

elementbo rder width

l

pix els

=bord erwidth? around arrows and slider

end line

next-after-last lin e index l

integer

text only;

exp ortselection

l

l

l l 1or0

1

f on t

l l l l l l l l l l l l l font 3 tuple

TkDefaultFo nt

name, s iz e, weigh t

foreground or - fg l l l l l l l l l l l l l color

system

from

ll

fp - lowest value

0.0

scale, spinbo x; used with to and in crement

han d lep ad

l

dis tance value

8

paned window; sash to handle distance

han d lesize

l

dis tance value

8

paned window; side len gth of sash handle

heig ht

ll l ll ll l l l

text-lines , image-

l l dis tance value

1

centered

highlightbackground l l l l l l l l l l l l l l l l color

system

highlightco lor

l l l l l l l l l l l l l l l l color

system

highlightthickness l l l l l l l l l l l l l l l l dis tance value

1 pixel

width of highlight if widget has inpu t focus

imag e

ll

l

l

l

bit flie: gif, pgm, ppm

image created with image_create co mmand

inactiv eselectbackgr o un d

l color

text; for selection when windo w does not have fo cus - n o d efault

increme nt

l

fp(can be + or -)

1.0

spinbox; widget adj amount

indicato ron

l

l

l

boolean

false

check, radio, m en u bu ttons; raised if true

insertbackg rou nd

ll

l l color

blac k

insertbo rderwidth

ll

l l dis tance value

0

insertofftime

ll

l l milliseconds

300

ins erton tim e

ll

l l milliseconds

600

ins ertun f oc us s ed

none,(no cursor), l hollow, solid

none

text; n ew in tcl8l.6

insertwid th

ll

l l dis tance value

2 pixels

width of insertion cursor

? 2021 John A. Oakey

JR2021D 5

TOOLBOX tkinter 0221 Toolbox Reference

For 3.5

Bu tto n C an vas Che ck button E ntry Fr ame La bel La belF rame Li stbox Me nu Me nubutton Me ssage PanedW indow Ra diobutton Sca le Scr oll bar S pin bo x T ext T opl evel

Widget Options and Attributes

Def aul t Value Type Value

Note

invalidcommand or invcmd

jump

justify label labelan ch or labelw idget leng th

listvariab le

maxu nd o men u offrelief offvalue on value op aq ueresize or ient

ove rrelief

pad x pad y po stcomman d pr oxybackground pr oxybor derw idth pr oxyre lief readonlybac kground relief rep eatdelay rep eatin terval resolu tio n

sa shcursor

sa shpad sa shrelief sa shwidth

screen

scrollr egion se lectbackground se lectborderwidth se lectcolor se lectforeground

se lectimage

se lectmode

se tgrid sh o w showha ndle sh o wvalue slid erleng th slid errelief sp acing 1

l

l

scrip t to evalu ate

-

spinbox, entry; best use is "bell"

boolean F-smooth T-

l

update at release

0

drag slider value change am t

l ll l

ll l l l

see justify cho ices string

center -

scale; label for the scale

l

compass points

"nw"

lableframe; text option can not be emp ty

l

widget

-

lableframe; widget to use as label

l

dis tance value

100

scale; lo ng dimension of the s cale

nam e of a global

l

variable

listbox; a list to be display in the widget

l integer

0

text; 0 or neg yield unlimited undo stack

l

l ass ociated menu n am e

toplevel, m enubu tton; ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download