associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

Revisão 8e 2005-05-11 04:13:05

Excluir mensagem

AdivinhacaoTkinter

Receita: Jogo de adivinhação

[attachment:AdivinhacaoTkinter.zip Baixe aqui o código completo]

A lógica desse jogo é que o usuário pensa em um número de 1 à 60, e selecionando as tabelas em que o número aparece, o jogo adivinha o número que o usuário pensou.

Este exemplo mostra como trabalhar com o Tkinter para carregar imagens, criar frames, trabalhar com botões e caixas de checagem, messagebox.

Esse jogo foi criado com o intuito de utilizar Python para gerar progrmas em modo gráfico, sem ter que recorrer a instalação de novos recursos como PyGame, PyGTK.

Código

   1 # -*- coding: cp1252 -*-
   2 import Tkinter; Tk = Tkinter
   3 import tkMessageBox
   4 
   5 class App(Tk.Frame):
   6     def __init__(self, master = None):
   7         Tk.Frame.__init__ (self, master)
   8 
   9 #cria o Frame e seta as variáveis do jogo
  10 
  11         self.varA = Tk.IntVar()
  12         self.varB = Tk.IntVar()
  13         self.varC = Tk.IntVar()
  14         self.varD = Tk.IntVar()
  15         self.varE = Tk.IntVar()
  16         self.varF = Tk.IntVar()
  17 
  18 # carrega as imagens 
  19 
  20     def criaImagens(self):
  21         self.__image_runner1__ = Tk.PhotoImage('runner1',file="1.gif")
  22         self.__image_runner2__ = Tk.PhotoImage('runner2',file="2.gif")
  23         self.__image_runner3__ = Tk.PhotoImage('runner3',file="3.gif")
  24         self.__image_runner4__ = Tk.PhotoImage('runner4',file="4.gif")
  25         self.__image_runner5__ = Tk.PhotoImage('runner5',file="5.gif")
  26         self.__image_runner6__ = Tk.PhotoImage('runner6',file="6.gif")
  27 
  28 # seta onde as imagens devem ser carregadas
  29 
  30         self.img_1 = Tk.Label (self,  {'image' : 'runner1'})
  31         self.img_2 = Tk.Label (self,  {'image' : 'runner2'})
  32         self.img_3 = Tk.Label (self,  {'image' : 'runner3'})
  33         self.img_4 = Tk.Label (self,  {'image' : 'runner4'})
  34         self.img_5 = Tk.Label (self,  {'image' : 'runner5'})
  35         self.img_6 = Tk.Label (self,  {'image' : 'runner6'})
  36 
  37 #cria as caixas de checagem atribuindo a variável usada
  38 
  39     def criaCheck(self):
  40         self.a = Tk.Checkbutton(self, variable=self.varA)
  41         self.b = Tk.Checkbutton(self, variable=self.varB)
  42         self.c = Tk.Checkbutton(self, variable=self.varC)
  43         self.d = Tk.Checkbutton(self, variable=self.varD)
  44         self.e = Tk.Checkbutton(self, variable=self.varE)
  45         self.f = Tk.Checkbutton(self, variable=self.varF)
  46 
  47 #cria os botões  
  48 
  49     def criaBot(self):
  50         self.btOK=Tk.Button(self, text = "Resultado", command=self.btOK)
  51         self.btSAIR=Tk.Button(self, text = "Sair", command=self.btSAIR)
  52 
  53 #configura as linhas e colunas do frame, que serão usadas para carregar as imagens, botões e caixas de checagem
  54 
  55     def configuraFrame(self):
  56         self.rowconfigure (1, {'weight' : 1, 'minsize' : 30})
  57         self.rowconfigure (2, {'weight' : 0, 'minsize' : 30})
  58         self.rowconfigure (3, {'weight' : 0, 'minsize' : 30})
  59         self.rowconfigure (4, {'weight' : 0, 'minsize' : 30})
  60         self.columnconfigure (1, {'weight' : 0, 'minsize' : 30})
  61         self.columnconfigure (2, {'weight' : 0, 'minsize' : 30})
  62         self.columnconfigure (3, {'weight' : 0, 'minsize' : 30})
  63         self.columnconfigure (4, {'weight' : 0, 'minsize' : 30})
  64         self.columnconfigure (5, {'weight' : 0, 'minsize' : 30})
  65 
  66 #coloca o objeto(caixas, botões e imagens) em suas posições na tela (coluna x linha)
  67 
  68     def posicionaObjetos(self):
  69         self.img_1.grid({
  70               'in' : self,
  71               'column' : '1',
  72               'row' : '1',
  73               'sticky' : ''
  74               })
  75 
  76         self.img_2.grid({
  77               'in' : self,
  78               'column' : '2',
  79               'row' : '1',
  80               'sticky' : ''
  81               })
  82 
  83         self.img_3.grid({
  84               'in' : self,
  85               'column' : '3',
  86               'row' : '1',
  87               'sticky' : ''
  88               })
  89 
  90         self.img_4.grid({
  91               'in' : self,
  92               'column' : '1',
  93               'row' : '3',
  94               'sticky' : ''
  95               })
  96 
  97         self.img_5.grid({
  98               'in' : self,
  99               'column' : '2',
 100               'row' : '3',
 101               'sticky' : ''
 102               })
 103 
 104         self.img_6.grid({
 105               'in' : self,
 106               'column' : '3',
 107               'row' : '3',
 108               'sticky' : ''
 109               })
 110 
 111         self.a.grid({
 112               'in' : self,
 113               'column' : '1',
 114               'row' : '2',
 115               'sticky' : ''
 116               })
 117 
 118         self.b.grid({
 119               'in' : self,
 120               'column' : '2',
 121               'row' : '2',
 122               'sticky' : ''
 123               })
 124 
 125         self.c.grid({
 126               'in' : self,
 127               'column' : '3',
 128               'row' : '2',
 129               'sticky' : ''
 130               })
 131 
 132         self.d.grid({
 133               'in' : self,
 134               'column' : '1',
 135               'row' : '4',
 136               'sticky' : ''
 137               })
 138 
 139         self.e.grid({
 140               'in' : self,
 141               'column' : '2',
 142               'row' : '4',
 143               'sticky' : ''
 144               })
 145 
 146         self.f.grid({
 147               'in' : self,
 148               'column' : '3',
 149               'row' : '4',
 150               'sticky' : ''
 151               })
 152 
 153         self.btOK.grid({
 154               'in' : self,
 155               'column' : '2',
 156               'row' : '5',
 157               'sticky' : ''
 158               })
 159         self.btSAIR.grid({
 160               'in' : self,
 161               'column' : '3',
 162               'row' : '5',
 163               'sticky' : ''
 164               })
 165 #cria a função de retorno das variáveis das checkbox
 166 
 167     def pegarA(self):
 168         return self.varA.get()
 169 
 170     def pegarB(self):
 171         return self.varB.get()
 172 
 173     def pegarC(self):
 174         return self.varC.get()
 175 
 176     def pegarD(self):
 177         return self.varD.get()
 178 
 179     def pegarE(self):
 180         return self.varE.get()
 181 
 182     def pegarF(self):
 183         return self.varF.get()
 184 
 185 #desenha a tela    
 186 
 187     def mostraFrame(self, **packOptions):
 188         self.pack(packOptions)
 189 
 190     
 191     def setres(self,res):
 192         self.res = res
 193     
 194 #define as funções do botão sair (fechar o jogo)
 195 
 196     def btSAIR(self):
 197         self.master.destroy()
 198         self.destroy()
 199 
 200 #define as funções do botão OK (pegar o valor das variáveis)
 201 
 202     def btOK(self):
 203         self.res.calcula(self)
 204         self.varA.set(0)
 205         self.varB.set(0)
 206         self.varC.set(0)
 207         self.varD.set(0)
 208         self.varE.set(0)
 209         self.varF.set(0)
 210 
 211         
 212 #faz o calculo do número pensado, seguindo a lógica que se a primeira checkbox for selecionada o valor será 1, a segunda será 2, a terceira será 4, a quarta será 8, a quinta 16 e sexta 32. Pois a soma dos variáveis onde o número pensado aparece utiliza-se desta regra para dar a resposta ao usuário
 213 
 214 class Resultado(Tk.Frame):
 215     def calcula(self,app):
 216         self.x = 0
 217         if app.pegarA() == 1:
 218             self.x+= 1
 219         if app.pegarB() == 1:
 220             self.x+= 2
 221         if app.pegarC() == 1:
 222             self.x+= 4
 223         if app.pegarD() == 1:
 224             self.x+= 8
 225         if app.pegarE() == 1:
 226             self.x+= 16
 227         if app.pegarF() == 1:
 228             self.x+= 32
 229 
 230         res = self.montaTela()
 231         return res
 232 #cria a tela do resultado
 233         
 234     def montaTela(self, master2=None):
 235 
 236         if self.x <= 0:
 237             res = tkMessageBox.showinfo("RESULTADO ", "Você não pensou em nenhum número")
 238         elif self.x > 60:
 239             res = tkMessageBox.showinfo("RESULTADO ", "Por favor pense em números de 1 a 60")
 240         else:
 241             res = tkMessageBox.showinfo("RESULTADO ", "Você pensou no número: "+str(self.x)) 
 242 
 243         return res
 244    
 245     def btSAIR(self):
 246         self.master2.destroy()
 247 #cria o aplicativo propriamente dito        
 248 def inicia():
 249     app = App()
 250     res = Resultado()
 251 
 252     app.setres(res)
 253     app.criaImagens()
 254     app.criaCheck()
 255     app.criaBot()
 256     app.configuraFrame()
 257     app.posicionaObjetos()
 258     app.mostraFrame(fill = 'both', expand = 1)
 259  
 260     app.mainloop ()
 261 
 262 
 263 if __name__ == '__main__':
 264     inicia()

Volta para CookBook.


Fabio Meincheim <fabio.jgs@gmail.com> Graduando do curso de Sistemas de Informação IST - Instituto Superior Tupy de Joinville

Eduardo da Silva <eduardo.silva@gmail.com> Professor de programação do IST.