_14 - Programando Em Python - Interfaces Graficas Com Tk

download _14 - Programando Em Python - Interfaces Graficas Com Tk

of 92

Transcript of _14 - Programando Em Python - Interfaces Graficas Com Tk

  • Claudio Esperana

    Python:Python:Interfaces Grficas com TkInterfaces Grficas com Tk

  • Interfaces GrficasInterfaces Grficas TambmchamadasdeGraphicalUserInterfaces(GUI) Usadasemaplicaesmodernasquerequeremuma

    interaoconstantecomousurio Maiorusabilidadeenaturalidadedoqueinterfacestextuais

    Aplicaoapresentaumaoumaisjanelascomelementosgrficosqueservemparacomandaraes,especificarparmetros,desenhareexibirgrficos,etc

    Bibliotecas(toolkits)paraconstruodeinterfacescomo Qt Gtk wxWindows Tk

  • Interfaces Grficas em PythonInterfaces Grficas em Python

    Pythonpossuicamadasdeportabilidade(bindings)paravriasbibliotecasdeconstruodeinterfaces.Ex.: PyQt(Qt) PyGtk(Gtk) wxPython(wxWindows) Tkinter(Tk)

    Multiplataforma(MSWindows,Unix/Linux,OSX)

  • TkTk

    ToolkitoriginalmentecriadoparautilizaocomalinguagemscriptTcl

    Bastanteleve,porttilerobusto Umtantoobsoletofrenteaoutrostoolkitsmaismodernos

    comoQtouGtk CamadaTkinternormalmentedistribudacomoPython

    IniciaumprocessoTclquetomacontadoselementosdeinterface

    ClassesefunesdoTkintersecomunicamcomointerpretadorTclparaespecifcaraspectoecomportamentodainterface

  • Usando TkinterUsando Tkinter

    ImportaromduloTkinter from Tkinter import *

    Elementosdeinterface(widgets)correspondemaobjetosdediversasclasses.Porexemplo: Frame(rearetangular) Button(boto) Label(rtulo) Text(caixadetexto) Canvas(caixadedesenho)

    Posioetamanhodoselementoscontroladosporgerentesdegeometria Pack (maiscomum), Place, Grid

  • Usando Tkinter (2)Usando Tkinter (2)

    Paracriarumwidget,temsequeinformarowidgetpai(parmetromaster)ondegeometricamentedeverserencaixadoeasopesdeconfiguraoparaowidget.Ex.:w = Button(pai,text=Cancelar,command=cancelar)

    Tkjdefinepordefaultumajanelaprincipal master=None(default)indicaqueowidgetserfilhodajanelaprincipal

    OutrasjanelaspodesercriadascriandoobjetosdaclasseToplevel

    Afunomainlooptemqueserinvocadaparaqueaaplicaoentrenomododetratamentodeeventos

  • ExemploExemplo

    from Tkinter import *

    class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.msg = Label(self, text="Hello World") self.msg.pack () self.bye = Button (self, text="Bye", command=self.quit) self.bye.pack () self.pack()

    app = Application()mainloop()

  • ExemploExemplo

    from Tkinter import *

    class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.msg = Label(self, text="Hello World") self.msg.pack () self.bye = Button (self, text="Bye", command=self.quit) self.bye.pack () self.pack()

    app = Application()mainloop()

  • ExemploExemplo

    from Tkinter import *

    class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.msg = Label(self, text="Hello World") self.msg.pack () self.bye = Button (self, text="Bye", command=self.quit) self.bye.pack () self.pack()

    app = Application()mainloop()

    Elemento principal derivado de Frame

    Construtor da classe base

    Janela tem um rtulo e um boto

    Interface instanciada

    Lao de tratamento de eventos iniciado

  • Classes de componentesClasses de componentes

    ButtonUmbotosimplesusadoparaexecutarumcomando CanvasProvfacilidadesdegrficosestruturados CheckbuttonRepresentaumavarivelquepodeterdois

    valoresdistintos(tipicamenteumvalorbooleano).Clicandonobotoalternaseentreosvalores

    EntryUmcampoparaentradadeumalinhadetexto FrameUsadocomoagrupadordewidgets LabelMostraumtextoouumaimagem ListboxMostraumalistadealternativas.Podeser

    configuradoparatercomportamentodecheckbuttonouradiobutton

  • Classes de componentes (cont.)Classes de componentes (cont.) MenuUmpaineldemenu.Implementamenusdejanela,pulldownse

    popups MessageSimilaraowidgetLabel,mastemmaisfacilidadepara

    mostrartextoquebradoemlinhas RadiobuttonRepresentaumpossvelvalordeumavarivelque

    temumdemuitosvalores.Clicandooboto,avarivelassumeaquelevalor

    ScalePermiteespecificarumvalornumricoatravsdeumponteiroemumaescalalinear

    ScrollbarBarraderolamentoparawidgetsquetmsuperfcietilvarivel(Text,Canvas,Entry,Listbox)

    TextExibeepermiteeditartextoformatado.Tambmsuportaimagensejanelasembutidas

    ToplevelUmajanelaseparada

  • A Classe TkA Classe Tk

    aquedefineumajanelaprincipaleointerpretadorTcl Emgeral,nuncaprecisaserinstanciada

    instanciadaautomaticamentequandoumwidgetfilhocriado

    Podeserinstanciadaexplicitamente Possuivriosmtodos,entreosquais

    title(string)Especificaottulodajanela geometry(string)Especificatamanhoeposiodajanela

    Stringtemaformalarguraxaltura+x+y

  • ExemploExemplofrom Tkinter import *

    class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.msg = Label(self, text="Hello World") self.msg.pack () self.bye = Button (self, text="Bye", command=self.quit) self.bye.pack () self.pack()

    app = Application()app.master.title("Exemplo")app.master.geometry("200x200+100+100")mainloop()

  • Opes de Opes de WidgetsWidgets

    Widgets(elementosdeinterface)tmopescomnomenclaturaunificada.Ex.: textTextomostradonoelemento backgroundcordefundo foregroundcordotexto fontfontedotexto reliefrelevodaborda('flat','raised','ridge','sunken', 'groove')

    Opessoespecificadas Noconstrutor Atravsdomtodoconfigure

  • ExemploExemplofrom Tkinter import *top = Frame() ; top.pack()rotulo = Label (top, text="Rtulo Exemplo",

    foreground="blue") rotulo.pack ()rotulo.configure(relief="ridge", font="Arial 24 bold",

    border=5, background="yellow")

  • O mtodo configureO mtodo configure Usadocomparesdotipoopo=valor,modificaosvaloresdos

    atributos Usadocomumastringnomeoporetornaaconfiguraoda

    opocomessenome Aconfiguraoumatuplacom5valores

    nomedoatributo nomedoatributonobancodedados(X11) nomedaclassenobancodedados(X11) objetoquerepresentaaopo valorcorrentedaopo

    Seconfigureusadosemargumentos,retornaumdicionriocomtodasasopes

    Podeseobterdiretamenteovalordeumaopousandoomtodocget

  • ExemploExemplo

    >>> rotulo.configure(relief="ridge")>>> rotulo.configure("relief")('relief', 'relief', 'Relief', , 'ridge')>>> rotulo.configure()["relief"]('relief', 'relief', 'Relief', , 'ridge')>>> rotulo.configure("relief")[4]'ridge'>>> rotulo.cget("relief")'ridge'

  • Gerenciando geometriasGerenciando geometrias

    Todososelementosdeinterfaceocupamumarearetangularnajanela

    Aposioetamanhodecadaelementodeterminadaporumgerenciadordegeometria Oelementonoapareceenquantonoforinformadoaogerenciador

    Ageometriaresultantedependede Propriedadesdoselementos(tamanhomnimo,tamanhodamoldura,etc)

    Opesdogerenciador Algoritmousadopelogerenciador

    OgerenciadormaisusadoemTkopack

  • Usando o Usando o packpack

    Parainformarqueumelementodevesergerenciadopelopack,useomtodopack(opes)

    Opackconsideraoespaodoelementopaicomoumacavidadeaserpreenchidapeloselementosfilhos

    Oalgoritmousadopelopackconsisteemempacotarosfilhosdeumelementopaisegundoolado(side)especificado Osladospossveisso'top','left','right'e'bottom' Deveseimaginarquesemprequeumelementofilhoescolheumlado,acavidadedisponvelficarestritaaoladooposto

  • ExemploExemplo

    from Tkinter import *top = Frame() ; top.pack()a = Label (top, text="A") ; a.pack (side="left")b = Label (top, text="B") ; b.pack (side="bottom")c = Label (top, text="C") ; c.pack (side="right")d = Label (top, text="D") ; d.pack (side="top")for widget in (a,b,c,d): widget.configure(relief="groove", border=10,

    font="Times 24 bold")top.mainloop()

  • RedimensionamentoRedimensionamento Pordefault,opacknoredimensionaosfilhosquandoo

    pairedimensionado Duasopescontrolamoredimensionamentodosfilhos

    expand(booleano) Severdadeiro,indicaqueofilhodevetomartodaacavidadedisponvelnopai

    Casocontrrio,tomaapenasoespaonecessrio(default) fill('none','x','y'ou'both')

    Indicacomoodesenhodoelementoirpreencheroespaoalocado

    'x'/'y'indicaqueirpreencheralargura/altura 'both'indicapreenchimentodetodooespao 'none'indicaqueapenasoespaonecessrioserocupado(default)

  • ExemploExemplo

    from Tkinter import *top = Frame() ; top.pack()a = Label (top, text="A") ; a.pack (side="left",

    fill="y")b = Label (top, text="B") ; b.pack (side="bottom",

    fill="x")c = Label (top, text="C") ; c.pack (side="right")d = Label (top, text="D") ; d.pack (side="top")for widget in (a,b,c,d): widget.configure(relief="groove", border=10,

    font="Times 24 bold")top.mainloop()

  • ExemploExemplo

    from Tkinter import *top = Frame() ; top.pack()a = Label (top, text="A") ; a.pack (side="left",

    fill="y")b = Label (top, text="B") ; b.pack (side="bottom",

    fill="x")c = Label (top, text="C") ; c.pack (side="right")d = Label (top, text="D") ; d.pack (side="top")for widget in (a,b,c,d): widget.configure(relief="groove", border=10,

    font="Times 24 bold")top.mainloop()

  • ExemploExemplo

    from Tkinter import *top = Frame() ; top.pack(fill='both', expand=True)a = Label (top, text="A") ; a.pack

    (side="left",fill="y")b = Label (top, text="B") ; b.pack

    (side="bottom",fill="x")c = Label (top, text="C") ; c.pack (side="right")d = Label (top, text="D") ; d.pack (side="top")for widget in (a,b,c,d): widget.configure(relief="groove", border=10,

    font="Times 24 bold")top.mainloop()

  • ExemploExemplo

    from Tkinter import *top = Frame() ; top.pack(fill='both', expand=True)a = Label (top, text="A") ; a.pack

    (side="left",fill="y")b = Label (top, text="B") ; b.pack

    (side="bottom",fill="x")c = Label (top, text="C") ; c.pack (side="right")d = Label (top, text="D") ; d.pack (side="top")for widget in (a,b,c,d): widget.configure(relief="groove", border=10,

    font="Times 24 bold")top.mainloop()

  • ExemploExemplo

    from Tkinter import *top = Frame() ; top.pack(fill='both', expand=True)a = Label (top, text="A") ; a.pack

    (side="left",expand=True,fill="y")b = Label (top, text="B") ; b.pack

    (side="bottom",expand=True,fill="both")c = Label (top, text="C") ; c.pack (side="right")d = Label (top, text="D") ; d.pack (side="top")for widget in (a,b,c,d): widget.configure(relief="groove", border=10,

    font="Times 24 bold")top.mainloop()

  • ExemploExemplo

    from Tkinter import *top = Frame() ; top.pack(fill='both', expand=True)a = Label (top, text="A") ; a.pack

    (side="left",expand=True,fill="y")b = Label (top, text="B") ; b.pack

    (side="bottom",expand=True,fill="both")c = Label (top, text="C") ; c.pack (side="right")d = Label (top, text="D") ; d.pack (side="top")for widget in (a,b,c,d): widget.configure(relief="groove", border=10,

    font="Times 24 bold")top.mainloop()

  • Usando framesUsando frames

    Framespodemserusadosparaauxiliarnolayoutdoselementoscompack.Ex.:from Tkinter import *top = Frame() ; top.pack(fill='both', expand=True)f = Frame (top); f.pack (fill='x')a = Label (f, text="A") b = Label (f, text="B") c = Label (f, text="C") d = Label (top, text="D") for w in (a,b,c,d): w.configure(relief="groove", border=10, font="Times 24 bold")

    w.pack(side="left", expand=True, fill="both")top.mainloop()

  • Usando framesUsando frames

    Framespodemserusadosparaauxiliarnolayoutdoselementoscompack.Ex.:from Tkinter import *top = Frame() ; top.pack(fill='both', expand=True)f = Frame (top); f.pack (fill='x')a = Label (f, text="A") b = Label (f, text="B") c = Label (f, text="C") d = Label (top, text="D") for w in (a,b,c,d): w.configure(relief="groove", border=10, font="Times 24 bold")

    w.pack(side="left", expand=True, fill="both")top.mainloop()

  • Programao com eventosProgramao com eventos

    Diferentedaprogramaoconvencional Oprogramanoestsobcontrole100%dotempo

    Programaentregacontroleaosistema EmTk:mtodo(funo)mainloop

    Interaogeraeventos.Ex: Acionamentodeummenuoudeumboto Mousearrastadosobreumajanela Umacaixadetextoteveseuvaloralterado

    OtratamentodeumeventofeitoporumarotinaCallback

  • A opo A opo commandcommand

    MuitoscomponentesdoTksuportamaopocommandqueindicaumafunoaserinvocadasemprequeowidgetacionado

    Tipicamente,afuno(oumtodo)usadoobtmvaloresdeoutroswidgetspararealizaralgumaoperao

  • ExemploExemplo

    from Tkinter import *

    def inc(): n=int(rotulo.configure("text")[4])+1 rotulo.configure(text=str(n)) b = Button(text="Incrementa",command=inc)b.pack()rotulo = Label(text="0")rotulo.pack()mainloop()

  • ExemploExemplo

    from Tkinter import *

    def inc(): n=int(rotulo.configure("text")[4])+1 rotulo.configure(text=str(n)) b = Button(text="Incrementa",command=inc)b.pack()rotulo = Label(text="0")rotulo.pack()mainloop()

  • ExemploExemplo

    from Tkinter import *

    def inc(): n=int(rotulo.configure("text")[4])+1 rotulo.configure(text=str(n)) b = Button(text="Incrementa",command=inc)b.pack()rotulo = Label(text="0")rotulo.pack()mainloop()

  • Eventos e Eventos e BindBind

    Widgetsquenodispemdaopocommandtambmpodemrecebereventoseresponderaeles

    Omtodobindpermiteespecificarumpadrodeeventosaoqualowidgetsersensveleumarotinacallbackparatratlobind(padro,rotina) padroumastringquedescrevequaiseventosarotinairtratar

    rotinaumafunooumtodocomexatamenteumparmetro:oeventoquedevesertratado

  • ExemploExemplo

    from Tkinter import *

    def clica (e): txt = "Mouse clicado em\n%d,%d"%(e.x,e.y) r.configure(text=txt) r = Label()r.pack(expand=True, fill="both")r.master.geometry("200x200")r.bind("", clica)mainloop()

  • ExemploExemplo

    from Tkinter import *

    def clica (e): txt = "Mouse clicado em\n%d,%d"%(e.x,e.y) r.configure(text=txt) r = Label()r.pack(expand=True, fill="both")r.master.geometry("200x200")r.bind("", clica)mainloop()

  • ExemploExemplo

    from Tkinter import *

    def clica (e): txt = "Mouse clicado em\n%d,%d"%(e.x,e.y) r.configure(text=txt) r = Label()r.pack(expand=True, fill="both")r.master.geometry("200x200")r.bind("", clica)mainloop()

  • Campos do objeto eventoCampos do objeto evento

    x,y:posiodomousecomrelaoaocantosuperioresquerdodowidget

    x_root, y_root:posiodomousecomrelaoaocantosuperioresquerdodatela

    char:caracteredigitado(eventosdeteclado) keysym:representaosimblicadatecla keycode:representaonumricadatecla num:nmerodoboto1/2/3=Esquerdo/Meio/Direito

    (eventosdemouse) widget:oobjetoquegerouoevento width,height:larguraealturadowidget(eventoConfigure)

  • Padres de evento (mouse)Padres de evento (mouse)

    parai=1,2,3:botoidomousepressionadosobreowidget

    :mousearrastadosobreowidget :mousearrastadosobreowidgetcomobotoi

    pressionado :botoidomousesoltosobreowidget :botoidomouseclicadoduasvezes

    emseguida :Omouseentrounareadowidget :Omousesaiudareadowidget

  • Padres de evento (teclado)Padres de evento (teclado)

    caracter:Ocaracterfoidigitadosobreowidget :Algumcaracterfoidigitadosobreowidget :Teclaenterfoidigitada , , ...:Ateclacorrespondentefoidigitada , , ...:Teclacom

    modificador Paraoseventosseremgerados,precisoqueofocodeteclado

    estejasobreowidget Dependedosistemadejanelas Ofocoparaumwidgetpodeserforadousandoomtodofocus

  • ExemploExemplo

    from Tkinter import *def clica (e): txt = "Mouse clicado em\n%d,%d"%(e.x,e.y) r.configure(text=txt) r.focus()def tecla(e): txt="Keysym=%s\nKeycode=%s\nChar=%s"\ %(e.keysym,e.keycode,e.char) r.configure(text=txt)r = Label()r.pack(expand=True, fill="both")r.master.geometry("200x200")r.bind("", clica)r.bind("", tecla)

  • ExemploExemplo

    from Tkinter import *def clica (e): txt = "Mouse clicado em\n%d,%d"%(e.x,e.y) r.configure(text=txt) r.focus()def tecla(e): txt="Keysym=%s\nKeycode=%s\nChar=%s"\ %(e.keysym,e.keycode,e.char) r.configure(text=txt)r = Label()r.pack(expand=True, fill="both")r.master.geometry("200x200")r.bind("", clica)r.bind("", tecla)

  • ExemploExemplo

    from Tkinter import *def clica (e): txt = "Mouse clicado em\n%d,%d"%(e.x,e.y) r.configure(text=txt) r.focus()def tecla(e): txt="Keysym=%s\nKeycode=%s\nChar=%s"\ %(e.keysym,e.keycode,e.char) r.configure(text=txt)r = Label()r.pack(expand=True, fill="both")r.master.geometry("200x200")r.bind("", clica)r.bind("", tecla)

  • ExemploExemplo

    from Tkinter import *def clica (e): txt = "Mouse clicado em\n%d,%d"%(e.x,e.y) r.configure(text=txt) r.focus()def tecla(e): txt="Keysym=%s\nKeycode=%s\nChar=%s"\ %(e.keysym,e.keycode,e.char) r.configure(text=txt)r = Label()r.pack(expand=True, fill="both")r.master.geometry("200x200")r.bind("", clica)r.bind("", tecla)

  • ExemploExemplo

    from Tkinter import *def clica (e): txt = "Mouse clicado em\n%d,%d"%(e.x,e.y) r.configure(text=txt) r.focus()def tecla(e): txt="Keysym=%s\nKeycode=%s\nChar=%s"\ %(e.keysym,e.keycode,e.char) r.configure(text=txt)r = Label()r.pack(expand=True, fill="both")r.master.geometry("200x200")r.bind("", clica)r.bind("", tecla)

  • MenusMenus

    Podemserassociadosaumajanela(menustoplevel),pulldown,popupeemcascataapartirdeoutromenu

    TodossoinstnciasdaclasseMenu Ummenucompostodeitensquepodemser

    commandquandopressionadoexecutaumacallback checkboxparecidocomcommand,mastemumvalorbooleanoassociado

    radiobuttoncomocommand,masrepresentaumdevriosestadosmutuamenteexclusivos

    cascadeativaumoutromenuemcascata Paraadicionarumitemaummenu,usemtodosda

    formaadd(tipo,opes)ouadd_tipo(opes)

  • Menu de janela (toplevel)Menu de janela (toplevel)

    tipicamenteexibidohorizontalmentenotopodajanela Aspectodependedosistemaoperacional

    Seumoutromenuassociadocomoitemcascade,eletratadocomopulldown,isto,exibidosoboitemdomenudejanela

    Assimcomooutrosmenus,nonecessitatersuageometriagerenciada(e.g.,packougrid)

    Paraassociaraumajanela,usaseaopomenudoobjetojanela.

  • Exemplo Exemplo

    from Tkinter import *def abrir(): print "abrir"def salvar(): print "salvar" def ajuda() : print "ajuda"top=Tk()principal=Menu(top)arquivo=Menu(principal)arquivo.add_command(label="Abrir",command=abrir)arquivo.add_command(label="Salvar",command=salvar)principal.add_cascade(label="Arquivo",menu=arquivo)principal.add_command(label="Ajuda",command=ajuda)top.configure(menu=principal)

  • Exemplo Exemplo

    from Tkinter import *def abrir(): print "abrir"def salvar(): print "salvar" def ajuda() : print "ajuda"top=Tk()principal=Menu(top)arquivo=Menu(principal)arquivo.add_command(label="Abrir",command=abrir)arquivo.add_command(label="Salvar",command=salvar)principal.add_cascade(label="Arquivo",menu=arquivo)principal.add_command(label="Ajuda",command=ajuda)top.configure(menu=principal)

  • Exemplo Exemplo

    from Tkinter import *def abrir(): print "abrir"def salvar(): print "salvar" def ajuda() : print "ajuda"top=Tk()principal=Menu(top)arquivo=Menu(principal)arquivo.add_command(label="Abrir",command=abrir)arquivo.add_command(label="Salvar",command=salvar)principal.add_cascade(label="Arquivo",menu=arquivo)principal.add_command(label="Ajuda",command=ajuda)top.configure(menu=principal)

  • Menus PopupMenus Popup

    Ummenupopupaquelequeexibidonumajanelaindependente

    Paraqueomenusejaexibido,precisoinvocaromtodopost:post (x, y) ondexeysoascoordenadasdocantosuperioresquerdodomenucomrelaoaocantosuperioresquerdodatela

  • ExemploExemplo

    from Tkinter import *

    def alo(): print "Alo!"

    root = Tk()menu = Menu(root, tearoff=0)menu.add_command(label="Alo 1", command=alo)menu.add_command(label="Alo 2", command=alo)

    def popup(e): menu.post(e.x_root, e.y_root)

    frame = Frame(root, width=200, height=200)frame.pack()frame.bind("", popup)mainloop()

  • ExemploExemplo

    from Tkinter import *

    def alo(): print "Alo!"

    root = Tk()menu = Menu(root, tearoff=0)menu.add_command(label="Alo 1", command=alo)menu.add_command(label="Alo 2", command=alo)

    def popup(e): menu.post(e.x_root, e.y_root)

    frame = Frame(root, width=200, height=200)frame.pack()frame.bind("", popup)mainloop()

  • VariveisVariveis TkcontroladoporuminterpretadorTcl(eno

    diretamentepelopython) Emalgunscasos,desejaseusarusarvariveisnainterface

    Porexemplo,possvelespecificarqueotextoexibidoemumLabelovalordeumavarivel(enoumaconstante) Nessecaso,usaseaopotextvaraoinvesdetext

    VariveisTclsoexpostasaplicaoPythonatravsdasclassesStringVar,IntVareDoubleVar OconstrutordaformaStringVar(master)ondemasterumajanelaouwidget

    InstnciasdessasclassespossuemosmtodosgetesetquepodemserusadosparaacessarosvaloresarmazenadosnointerpretadorTcl

  • ExemploExemplo

    from Tkinter import *

    root = Tk()soma = DoubleVar(root)parcela = DoubleVar(root)def aritmetica (e): soma.set(soma.get()+parcela.get()) lsoma = Label(textvar=soma)eparcela = Entry(textvar=parcela)eparcela.bind("", aritmetica)lsoma.pack()eparcela.pack()

  • ExemploExemplo

    from Tkinter import *

    root = Tk()soma = DoubleVar(root)parcela = DoubleVar(root)def aritmetica (e): soma.set(soma.get()+parcela.get()) lsoma = Label(textvar=soma)eparcela = Entry(textvar=parcela)eparcela.bind("", aritmetica)lsoma.pack()eparcela.pack()

  • ExemploExemplo

    from Tkinter import *

    root = Tk()soma = DoubleVar(root)parcela = DoubleVar(root)def aritmetica (e): soma.set(soma.get()+parcela.get()) lsoma = Label(textvar=soma)eparcela = Entry(textvar=parcela)eparcela.bind("", aritmetica)lsoma.pack()eparcela.pack()

  • ExemploExemplo

    from Tkinter import *

    root = Tk()soma = DoubleVar(root)parcela = DoubleVar(root)def aritmetica (e): soma.set(soma.get()+parcela.get()) lsoma = Label(textvar=soma)eparcela = Entry(textvar=parcela)eparcela.bind("", aritmetica)lsoma.pack()eparcela.pack()

  • CheckbuttonsCheckbuttons CheckbuttonRepresentaumavarivelquepodeterdois

    valoresdistintos(tipicamenteumvalorbooleano).Clicandonobotoalternaseentreosvalores

    Acallbackespecificadapelaopocommandchamadasemprequeavarivelmudadevalor

    EstadoarmazenadopelavarivelTclespecificadapelaopovariable

    Seavarivelinteira,ovalorcorrespondenteaocheckbuttondesligado/ligado0/1

    possvelusarumcheckbuttoncomumavarivelstring Nessecaso,osvalorescorrespondentesadesligado/ligadosoespecificadoscomasopesoffvalueeonvalue

  • ExemploExemplofrom Tkinter import *

    root = Tk()v1 = IntVar(root)v2 = StringVar(root)

    def exibe(): l.config (text="v1=%d,v2=%s"%(v1.get(),v2.get()))

    c1 = Checkbutton (text="V1", var=v1, command=exibe)c2 = Checkbutton (text="V2", var=v2, command=exibe,\ onvalue="Sim", offvalue="Nao")l = Label()for w in (c1,c2,l):w.pack()exibe()

  • ExemploExemplofrom Tkinter import *

    root = Tk()v1 = IntVar(root)v2 = StringVar(root)

    def exibe(): l.config (text="v1=%d,v2=%s"%(v1.get(),v2.get()))

    c1 = Checkbutton (text="V1", var=v1, command=exibe)c2 = Checkbutton (text="V2", var=v2, command=exibe,\ onvalue="Sim", offvalue="Nao")l = Label()for w in (c1,c2,l):w.pack()exibe()

  • ExemploExemplofrom Tkinter import *

    root = Tk()v1 = IntVar(root)v2 = StringVar(root)

    def exibe(): l.config (text="v1=%d,v2=%s"%(v1.get(),v2.get()))

    c1 = Checkbutton (text="V1", var=v1, command=exibe)c2 = Checkbutton (text="V2", var=v2, command=exibe,\ onvalue="Sim", offvalue="Nao")l = Label()for w in (c1,c2,l):w.pack()exibe()

  • ExemploExemplofrom Tkinter import *

    root = Tk()v1 = IntVar(root)v2 = StringVar(root)

    def exibe(): l.config (text="v1=%d,v2=%s"%(v1.get(),v2.get()))

    c1 = Checkbutton (text="V1", var=v1, command=exibe)c2 = Checkbutton (text="V2", var=v2, command=exibe,\ onvalue="Sim", offvalue="Nao")l = Label()for w in (c1,c2,l):w.pack()exibe()

  • RadiobuttonsRadiobuttons

    Radiobuttonrepresentaumpossvelvalordeumavarivelquetemumdemuitosvalores.Clicandooboto,avarivelassumeaquelevalor

    Avarivelespecificadacomaopovariableeovalorassociadocomaopovalue

    Osradiobuttonsquesereferemmesmavarivelfuncionamemconjunto Ex.:ligarumfazcomqueoutrosejadesligado

    Umradiobuttonmostradocomumindicadoraolado Podesedesabilitaroindicadorusandoaopcaoindicatoron=False

    Nessecaso,mostradocomoumbotonormal

  • ExemploExemplo

    from Tkinter import *root=Tk()cor = StringVar(root)cor.set("black")l = Label(background=cor.get())l.pack(fill='both',expand=True)def pinta(): l.configure(background=cor.get())for txt,val in (("preto","black"),\ ("vermelho","red"),\ ("azul","blue"), ("verde","green")): Radiobutton(text=txt,value=val,variable=cor,\ command=pinta).pack(anchor=W)mainloop()

  • ExemploExemplo

    from Tkinter import *root=Tk()cor = StringVar(root)cor.set("black")l = Label(background=cor.get())l.pack(fill='both',expand=True)def pinta(): l.configure(background=cor.get())for txt,val in (("preto","black"),\ ("vermelho","red"),\ ("azul","blue"), ("verde","green")): Radiobutton(text=txt,value=val,variable=cor,\ command=pinta).pack(anchor=W)mainloop()

  • ExemploExemplo

    from Tkinter import *root=Tk()cor = StringVar(root)cor.set("black")l = Label(background=cor.get())l.pack(fill='both',expand=True)def pinta(): l.configure(background=cor.get())for txt,val in (("preto","black"),\ ("vermelho","red"),\ ("azul","blue"), ("verde","green")): Radiobutton(text=txt,value=val,variable=cor,\ command=pinta).pack(anchor=W)mainloop()

  • ExemploExemplo

    from Tkinter import *root=Tk()cor = StringVar(root)cor.set("black")l = Label(background=cor.get())l.pack(fill='both',expand=True)def pinta(): l.configure(background=cor.get())for txt,val in (("preto","black"),\ ("vermelho","red"),\ ("azul","blue"), ("verde","green")): Radiobutton(text=txt,value=val,variable=cor,\ command=pinta).pack(anchor=W)mainloop()

  • ExemploExemplo

    from Tkinter import *root=Tk()cor = StringVar(root)cor.set("black")l = Label(background=cor.get())l.pack(fill='both',expand=True)def pinta(): l.configure(background=cor.get())for txt,val in (("preto","black"),\ ("vermelho","red"),\ ("azul","blue"), ("verde","green")): Radiobutton(text=txt,value=val,variable=cor,\ command=pinta,indicatoron=False).pack(fill='x')mainloop()

  • ExemploExemplo

    from Tkinter import *root=Tk()cor = StringVar(root)cor.set("black")l = Label(background=cor.get())l.pack(fill='both',expand=True)def pinta(): l.configure(background=cor.get())for txt,val in (("preto","black"),\ ("vermelho","red"),\ ("azul","blue"), ("verde","green")): Radiobutton(text=txt,value=val,variable=cor,\ command=pinta,indicatoron=False).pack(fill='x')mainloop()

  • EntryEntry UmEntrypermiteentrada/ediodeumalinhadetexto OtextoassociadoaoEntrynormalmentearmazenado

    numavarivelindicadapelaopotextvariable Senoindicada,usadaumavarivelinternacujovalorpodeserobtidousandoomtodoget()

    Hdiversosmtodosparamanipulardiretamenteotexto Usamoconceitodendices(noconfundircomosndicesusadopeloPython)

    Porexemplo,ondiceINSERTindicaaposiodotextoondeocursordeinseroseencontra,0aposioantesdoprimeirocaractereeENDaposioaofinaldotexto

  • ExemploExemplo

    from Tkinter import *def insere(): e.insert(INSERT,"*")def limpa(): e.delete(INSERT,END)e=Entry(font="Arial 24")i=Button(text="Insere*",command=insere)l=Button(text="Limpa",command=limpa)e.pack()for w in (i,l): w.pack(side='left')mainloop()

  • ExemploExemplo

    from Tkinter import *def insere(): e.insert(INSERT,"*")def limpa(): e.delete(INSERT,END)e=Entry(font="Arial 24")i=Button(text="Insere*",command=insere)l=Button(text="Limpa",command=limpa)e.pack()for w in (i,l): w.pack(side='left')mainloop()

  • ExemploExemplo

    from Tkinter import *def insere(): e.insert(INSERT,"*")def limpa(): e.delete(INSERT,END)e=Entry(font="Arial 24")i=Button(text="Insere*",command=insere)l=Button(text="Limpa",command=limpa)e.pack()for w in (i,l): w.pack(side='left')mainloop()

  • ExemploExemplo

    from Tkinter import *def insere(): e.insert(INSERT,"*")def limpa(): e.delete(INSERT,END)e=Entry(font="Arial 24")i=Button(text="Insere*",command=insere)l=Button(text="Limpa",command=limpa)e.pack()for w in (i,l): w.pack(side='left')mainloop()

  • CanvasCanvas

    Permiteaexibioeediodegrficosestruturados2D Elementosgrficos(itens)sointroduzidosusando

    mtodosdaformacreate_tipo(...),ondetipopodeser arcarcodecrculo bitmapimagembinria imageimagemcolorida linelinhapoligonal ovalcrculoseelipses polygonpolgonos rectangleretngulo texttexto windowumwidgettk

  • ExemploExemplofrom Tkinter import *c = Canvas()c.pack()o = c.create_oval(1,1,200,100,outline="blue",\

    width=5,fill="red")widget = Button(text="Tk Canvas")w = c.create_window(10,120,window=widget,anchor=W)l = c.create_line(100,0,120,30,50,60,100,120,\

    fill="black",width=2)r = c.create_rectangle(40,150,100,200,fill="white")img = PhotoImage(file="python.gif")i = c.create_image (150,150,image=img,anchor=NW)a = c.create_arc (150,90,250,190,start=30,extent=60,\

    outline="green",fill="orange")t = c.create_text(200,35,text="Texto\nTexto",

    font="Arial 22")

  • ExemploExemplofrom Tkinter import *c = Canvas()c.pack()o = c.create_oval(1,1,200,100,outline="blue",\

    width=5,fill="red")widget = Button(text="Tk Canvas")w = c.create_window(10,120,window=widget,anchor=W)l = c.create_line(100,0,120,30,50,60,100,120,\

    fill="black",width=2)r = c.create_rectangle(40,150,100,200,fill="white")img = PhotoImage(file="python.gif")i = c.create_image (150,150,image=img,anchor=NW)a = c.create_arc (150,90,250,190,start=30,extent=60,\

    outline="green",fill="orange")t = c.create_text(200,35,text="Texto\nTexto",

    font="Arial 22")

  • Coordenadas de ItensCoordenadas de Itens Todososmtodoscreate_itemtmcomoprimeiros

    argumentosumpardecoordenadasx,ydoitem Ositensovalerectanglerequeremmaisumpardecoordenadasparadelimitaraextenso(caixaenvolvente)

    Ositenslineepolygonpodemserseguidosporoutrosparesdecoordenadasqueespecificamdemaisvrtices

    Ascoordenadasreferemseaumsistemadecoordenadasprprioquepodeserdiferentedodajanela Areadocanvasquedevesermostradanajanelapodesermodificadapelaoposcrollarea=(xmin,ymin,xmax,ymax)

    Paraobterascoordenadasdocanvasdadasascoordenadasdajanelausaseosmtodoscanvasx(x)ecanvasy(y)

  • Identificao de ItensIdentificao de Itens Todoitemdeumcanvastemumidentificadornumrico

    queretornadopelomtodocreate_item Podesetambmassociartags(etiquetas)aitens

    Usaseaopotags=tagsondetagspodeserumastringouumatuplacomvriasstrings

    Umamesmaetiquetapodeserassociadaamaisdeumitem OidentificadorALLrefereseatodosositensdocanvas OidentificadorCURRENTrefereseaoitemdocanvassob

    ocursordomouse Usadoemcallbacksdecanvasparaalterarpropriedadesdositensclicados

  • Mtodos de CanvasMtodos de Canvas

    itemconfig(itemOuTag,...)alteraopesdo(s)item(s) tag_bind(itemOuTag,padro,callback)associaumacallbacka

    umpadrodeeventossobreo(s)item(s) delete(itemOuTag)removeo(s)item(s) move(itemOuTag,dx,dy)transladao(s)item(s) coords(itemOuTag,x1,x2,..xN,yN)alteraascoordenadasdo(s)

    item(s) coords(item)retornaascoordenadasdoitem bbox(itemOuTag)retornaumatuplacomacaixaenvolvente

    dositens itemcget(item,opo)retornaovalordaopodadadoitem

  • ExemploExemplo

    from Tkinter import *c = Canvas()c.pack()def novalinha(e): x,y = c.canvasx(e.x), c.canvasy(e.y) c.create_line(x,y,x,y,tags="corrente")def estendelinha(e): x,y = c.canvasx(e.x), c.canvasy(e.y) coords = c.coords("corrente") + [x,y] c.coords("corrente",*coords)def fechalinha(e): c.itemconfig("corrente",tags=())c.bind("", novalinha)c.bind("", estendelinha)c.bind("", fechalinha)c.pack()

  • ExemploExemplo

    from Tkinter import *c = Canvas()c.pack()def novalinha(e): x,y = c.canvasx(e.x), c.canvasy(e.y) c.create_line(x,y,x,y,tags="corrente")def estendelinha(e): x,y = c.canvasx(e.x), c.canvasy(e.y) coords = c.coords("corrente") + [x,y] c.coords("corrente",*coords)def fechalinha(e): c.itemconfig("corrente",tags=())c.bind("", novalinha)c.bind("", estendelinha)c.bind("", fechalinha)c.pack()

  • ExemploExemplo

    from Tkinter import *c = Canvas()c.pack()def novalinha(e): x,y = c.canvasx(e.x), c.canvasy(e.y) c.create_line(x,y,x,y,tags="corrente")def estendelinha(e): x,y = c.canvasx(e.x), c.canvasy(e.y) coords = c.coords("corrente") + [x,y] c.coords("corrente",*coords)def fechalinha(e): c.itemconfig("corrente",tags=())c.bind("", novalinha)c.bind("", estendelinha)c.bind("", fechalinha)c.pack()

  • ExemploExemplo

    from Tkinter import *c = Canvas()c.pack()def novalinha(e): x,y = c.canvasx(e.x), c.canvasy(e.y) c.create_line(x,y,x,y,tags="corrente")def estendelinha(e): x,y = c.canvasx(e.x), c.canvasy(e.y) coords = c.coords("corrente") + [x,y] c.coords("corrente",*coords)def fechalinha(e): c.itemconfig("corrente",tags=())c.bind("", novalinha)c.bind("", estendelinha)c.bind("", fechalinha)c.pack()

  • ExemploExemplo

    ...def selecionalinha(e): global x0,y0 x0,y0 = c.canvasx(e.x), c.canvasy(e.y) c.itemconfig(CURRENT, tags="sel")def movelinha (e): global x0,y0 x1,y1 = c.canvasx(e.x), c.canvasy(e.y) c.move("sel",x1-x0,y1-y0) x0,y0=x1,y1def deselecionalinha(e): c.itemconfig("sel", tags=())c.bind("", selecionalinha)c.bind("", movelinha)c.bind("", deselecionalinha)

  • ExemploExemplo

    ...def selecionalinha(e): global x0,y0 x0,y0 = c.canvasx(e.x), c.canvasy(e.y) c.itemconfig(CURRENT, tags="sel")def movelinha (e): global x0,y0 x1,y1 = c.canvasx(e.x), c.canvasy(e.y) c.move("sel",x1-x0,y1-y0) x0,y0=x1,y1def deselecionalinha(e): c.itemconfig("sel", tags=())c.bind("", selecionalinha)c.bind("", movelinha)c.bind("", deselecionalinha)

  • ExemploExemplo

    ...def selecionalinha(e): global x0,y0 x0,y0 = c.canvasx(e.x), c.canvasy(e.y) c.itemconfig(CURRENT, tags="sel")def movelinha (e): global x0,y0 x1,y1 = c.canvasx(e.x), c.canvasy(e.y) c.move("sel",x1-x0,y1-y0) x0,y0=x1,y1def deselecionalinha(e): c.itemconfig("sel", tags=())c.bind("", selecionalinha)c.bind("", movelinha)c.bind("", deselecionalinha)

  • ScrollbarScrollbar

    Barrasderolamentosousadascomoutroswidgetscomreatilmaiordoquepodeserexibidanajanela(Canvas,Text,Listbox,Entry)

    Umabarraderolamentohorizontal(vertical)funcionachamandoomtodoxview (yview)dowidgetassociado Istofeitoconfigurandoaopocommanddabarra

    Poroutrolado,semprequeavisodowidgetmuda,abarraderolamentoprecisaseratualizada Istofeitoconfigurandoaopoxscrollcommand(ouyscrollcommand)dowidgetaomtodosetdabarra

  • ExemploExemplo

    from Tkinter import *lb = Listbox()lb.pack(side=LEFT,expand=True,fill="both")sb = Scrollbar()sb.pack(side=RIGHT,fill="y")sb.configure(command=lb.yview)lb.configure(yscrollcommand=sb.set)for i in range(100): lb.insert(END,i)

  • ExemploExemplo

    from Tkinter import *lb = Listbox()lb.pack(side=LEFT,expand=True,fill="both")sb = Scrollbar()sb.pack(side=RIGHT,fill="y")sb.configure(command=lb.yview)lb.configure(yscrollcommand=sb.set)for i in range(100): lb.insert(END,i)

    Slide 1Slide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9Slide 10Slide 11Slide 12Slide 13Slide 14Slide 15Slide 16Slide 17Slide 18Slide 19Slide 20Slide 21Slide 22Slide 23Slide 24Slide 25Slide 26Slide 27Slide 28Slide 29Slide 30Slide 31Slide 32Slide 33Slide 34Slide 35Slide 36Slide 37Slide 38Slide 39Slide 40Slide 41Slide 42Slide 43Slide 44Slide 45Slide 46Slide 47Slide 48Slide 49Slide 50Slide 51Slide 52Slide 53Slide 54Slide 55Slide 56Slide 57Slide 58Slide 59Slide 60Slide 61Slide 62Slide 63Slide 64Slide 65Slide 66Slide 67Slide 68Slide 69Slide 70Slide 71Slide 72Slide 73Slide 74Slide 75Slide 76Slide 77Slide 78Slide 79Slide 80Slide 81Slide 82Slide 83Slide 84Slide 85Slide 86Slide 87Slide 88Slide 89Slide 90Slide 91Slide 92