1. Bouncing Ball

  2. Fattoriale

  3. Calcolatrice

Bouncing Ball

Piccola animazione raffigurante una pallina che rimbalza contro i 4 lati di un rettangolo (realizzato da gennaro)

   1 import sys
   2 import thread
   3 from time import sleep
   4 from Tkinter import *
   5 
   6 class Animation:
   7 
   8       def __init__(self, x, y,
   9                    x_acceleration = 2,
  10                    y_acceleration = 2,
  11                    ball_dimension = 14,
  12                    animation_speed = 50):
  13 
  14           self.x = x
  15           self.y = y
  16           self.x_acceleration = x_acceleration
  17           self.y_acceleration = y_acceleration
  18           self.ball_dimension = ball_dimension
  19           self.animation_speed = animation_speed
  20 
  21           self.__stop = False
  22 
  23           self.__root = Tk()
  24           self.__root.minsize(324,268)
  25           self.__root.maxsize(324,268)
  26 
  27           self.__canvas = Canvas(self.__root,
  28                                  width = 320,
  29                                  height = 240,
  30                                  bg = "yellow")
  31           self.__canvas.pack()
  32 
  33           self.__canvas.create_rectangle(1,1,320,240, outline = "black")
  34 
  35           self.__id = self.__canvas.create_oval(x, y,
  36                                                 x+ball_dimension,
  37                                                 y+ball_dimension,
  38                                                 fill = "lightblue")
  39 
  40           self.__button_frame = Frame(self.__root)
  41           self.__button_frame.pack(padx = 1, fill = "x")
  42 
  43           self.__start_button = Button(self.__button_frame,
  44                                        text = "Start", bd = 1,
  45                                        command = self.start)
  46           self.__start_button.pack(side = LEFT)
  47 
  48           self.__stop_button = Button(self.__button_frame,
  49                                       text = "Stop", bd = 1,
  50                                       state = DISABLED,
  51                                       command = self.stop)
  52           self.__stop_button.pack(side = LEFT)
  53 
  54           self.__quit_button = Button(self.__button_frame,
  55                                       text = "Quit", bd = 1,
  56                                       command = sys.exit)
  57           self.__quit_button.pack(side = RIGHT)
  58 
  59       def __start(self):
  60           while not self.__stop:
  61               if self.x < 1 or self.x > (319-self.ball_dimension):
  62                   self.x_acceleration = -self.x_acceleration
  63 
  64               if self.y < 1 or self.y > (239-self.ball_dimension):
  65                   self.y_acceleration = -self.y_acceleration
  66 
  67               self.__canvas.move(self.__id, self.x_acceleration, self.y_acceleration)
  68               self.__canvas.update_idletasks()
  69 
  70               self.x += self.x_acceleration
  71               self.y += self.y_acceleration
  72 
  73               sleep(1.0/self.animation_speed)
  74 
  75       def start(self):
  76           self.__stop = False
  77           thread.start_new_thread(self.__start,())
  78           self.__start_button.configure(state = DISABLED)
  79           self.__stop_button.configure(state = NORMAL)
  80 
  81       def stop(self):
  82           self.__stop = True
  83           self.__start_button.configure(state = NORMAL)
  84           self.__stop_button.configure(state = DISABLED)
  85 
  86       def main(self): self.__root.mainloop()
  87 
  88 
  89 if __name__ == "__main__":
  90    a = Animation(154,114)
  91    a.main()

Fattoriale

Programma che calcola il fattoriale di un numero (realizzato da Beppe)

   1 #############################
   2 # Module:   fattoriale.py
   3 # Authors:  Giuseppe Costanzi mailto[g.costanzi@email.it]         
   4 # Date:     29/04/2008
   5 # Version:  0.1 (alpha)
   6 # web:      Python-it.org  
   7 # Description: fattoriale start file
   8 #############################
   9 
  10 from Tkinter import *
  11 import tkMessageBox
  12 import time
  13 import sys,traceback
  14 from string import strip
  15 import string
  16 import data
  17 #import pdb
  18 AppTitle = 'Calcola Fattoriale'
  19 
  20 
  21 class Main():
  22     def __init__(self, master):
  23         #width height and coordinates
  24         master.geometry('400x210+200+200')
  25         master.title('Fattoriale')
  26         self.StatusBarText = StringVar()
  27         rgb_pn = "#5071ab"
  28 
  29         #menu
  30         mnuMain = Menu(master, bd = 1)
  31 
  32         mFile = Menu(mnuMain, tearoff=0, bd = 1)
  33         mAbout = Menu(mnuMain, tearoff=0, bd = 1)
  34 
  35         mnuMain.add_cascade(label="File", menu=mFile)
  36         mnuMain.add_cascade(label="Info", menu=mAbout)
  37 
  38         mFile.add_command(label="Exit",command=OnExit)
  39         mAbout.add_command(label="About", command=self.OnAbout)
  40 
  41         master.config(menu=mnuMain)
  42 
  43         #statusbar
  44         self.StatusBarText = 'www.Python-it.org'
  45         self.StatusBar = Label(master, text = self.StatusBarText, bd=1, relief=SUNKEN, anchor=W)
  46         self.StatusBar.pack(side=BOTTOM,fill=X)
  47 
  48         #panels
  49         self.MainPanel = LabelFrame(master,text='Calcola il fattoriale di n',
  50                                bg=rgb_pn,
  51                                relief=GROOVE)
  52 
  53         self.FirstPanel = LabelFrame(self.MainPanel,
  54                            bd=2,
  55                            relief=GROOVE,
  56                            padx=10,
  57                            pady=10)
  58 
  59         self.SecondPanel = LabelFrame(self.MainPanel,text='Comandi',
  60                             bd=2,
  61                             bg= rgb_pn ,
  62                             relief=GROOVE,
  63                             padx=10,
  64                             pady=10)
  65 
  66 
  67         #widgets
  68         self.stN = Label(self.FirstPanel, text='n=')
  69         self.txN = Entry(self.FirstPanel,bg='white')
  70 
  71         self.stResult = Label(self.FirstPanel, text='n!=')
  72         self.txResult=Entry(self.FirstPanel,relief=GROOVE,bg='lightyellow')
  73 
  74         self.btCalcola = Button(self.SecondPanel, text="Calcola",width=10, command=self.OnCalculate)
  75         self.btCancella = Button(self.SecondPanel, text="Cancella",width=10, command=self.OnClear)
  76         self.btEsci = Button(self.SecondPanel, text="Esci",width=10, command=OnExit)
  77 
  78         #packing
  79         self.MainPanel.pack(side=TOP,fill=BOTH,expand=0)
  80         self.FirstPanel.pack(side=LEFT,fill=X,padx = 10,expand=0)
  81         self.stN.grid(row=0, column=0,sticky=W)
  82         self.txN.grid(row=0, column=1,sticky=W)
  83         self.stResult.grid(row=1, column=0,sticky=W)
  84         self.txResult.grid(row=1, column=1)
  85         self.SecondPanel.pack(side=RIGHT,fill=X,padx = 10,expand=0)
  86         self.btCalcola.pack(padx = 3, pady = 8)
  87         self.btCancella.pack(padx = 3, pady = 8)
  88         self.btEsci.pack(padx = 3, pady = 8)
  89 
  90 
  91 
  92     #event handler
  93     def OnOpen(self):
  94         self.txN.focus_set()
  95 
  96     def OnClear(self):
  97         self.txN.delete(0, END)
  98         self.txResult.delete(0, END)
  99         self.txN.focus_set()
 100 
 101     def OnFieldsControl(self):
 102         sN = (self.txN.get())
 103         if len(sN)==0:
 104                 message="Attenzione!\nLa casella e\' vuota!"
 105                 tkMessageBox.showinfo(AppTitle,message)
 106                 self.txN.focus_set()
 107                 return 0
 108 
 109     def OnCalculate(self):
 110 
 111         self.txResult.delete(0, END)
 112 
 113         if self.OnFieldsControl()==0:
 114             return
 115 
 116         n = (self.txN.get())
 117 
 118         try:
 119 
 120             ret = data.Fattoriale(int(n))
 121 
 122             if ret == -1 :
 123                 message = "Errore:\nIl fattoriale e' definito solo per i valori interi."
 124                 tkMessageBox.showinfo(AppTitle,message)
 125             elif ret == -2 :
 126                 message = "Errore:\nIl fattoriale e' definito solo per interi positivi."
 127                 tkMessageBox.showinfo(AppTitle,message)
 128             else:
 129                 self.txResult.insert(END, ret)
 130 
 131         except:
 132             sModule = '\nModule: fattoriale.py'
 133             sFunction ='\nFunction: OnCalculate'
 134             sParameter ='\nInput parameter: %s' %('Nothing')
 135             excValue = '\nException value: %s ' %(str(sys.exc_value))
 136             excType = '\nException type: %s ' %(str(sys.exc_type))
 137             logTime = time.localtime(time.time())
 138             FormatlogTime = time.strftime("%d/%m/%Y %H:%M:%S", logTime)
 139             sFormatLog = ("Except Data: %s" % (FormatlogTime))
 140             fLog = open('log.txt','a')
 141             sReportException = "\n%s%s%s%s%s%s "%(sFormatLog,
 142                                                     sModule,
 143                                                     sFunction,
 144                                                     sParameter,
 145                                                     excValue,
 146                                                     excType)
 147 
 148             fLog.write (sReportException)
 149             fLog.close()
 150             message="Houston,We've got a problem!\n%s" % (sReportException)
 151             tkMessageBox.showinfo(AppTitle,message)
 152 
 153     def OnAbout(self):
 154         info = data.Fattoriale.__doc__
 155         message = "Fattoriale\ndeveloped in Tkinter by\nGiuseppe Costanzi Python-it.org\n%s"%(info)
 156         tkMessageBox.showinfo(AppTitle,message)
 157 
 158 def OnExit():
 159     if tkMessageBox.askokcancel(AppTitle, "Chiudere il programma?"):
 160         root.destroy()
 161 
 162 if __name__ == '__main__':
 163 
 164     root=Tk()
 165     app = Main(root)
 166     app.OnOpen()
 167     root.resizable(0,0)
 168     root.protocol("WM_DELETE_WINDOW",OnExit)
 169     root.mainloop()

Calcolatrice

Calcolatrice (realizzata da gennaro)

   1 from Tkinter import *
   2 
   3 class Calculator:
   4 
   5     def __init__(self):
   6         self.__root = Tk()
   7         self.__root.minsize(300,200)
   8         self.__root.title("Calcultor")
   9 
  10         self.__buttons = (("7",1,0),
  11                           ("8",1,1),
  12                           ("9",1,2),
  13                           ("/",1,3),
  14                           ("4",2,0),
  15                           ("5",2,1),
  16                           ("6",2,2),
  17                           ("*",2,3),
  18                           ("1",3,0),
  19                           ("2",3,1),
  20                           ("3",3,2),
  21                           ("-",3,3),
  22                           ("0",4,0),
  23                           (".",4,1),
  24                           ("+",4,3))
  25 
  26         self._make_buttons()
  27 
  28         self.__display = Label(self.__root, bg = "white", relief = "sunken", height = 2, anchor = E)
  29         self.__display.grid(row = 0, column = 0, columnspan = 3, sticky=N+S+E+W)
  30 
  31         # Make the window resizable
  32         for i in range(1,5): self.__root.rowconfigure(i, weight = 1)
  33         for i in range(4): self.__root.columnconfigure(i, weight = 1)
  34 
  35 
  36     def _make_buttons(self):
  37         for b in self.__buttons:
  38             def f(arg = b[0]): self.__display["text"] += arg
  39             Button(self.__root, text = b[0], command = f).grid(row = b[1], column = b[2], sticky=N+S+E+W)
  40 
  41         Button(self.__root, text = "Clear", command = self._clear_display).grid(row = 0, column = 3, sticky=N+S+E+W)
  42         Button(self.__root, text = "=", command = self._calculate).grid(row = 4, column = 2, sticky=N+S+E+W)
  43 
  44     def _calculate(self):
  45         try: self.__display["text"] = str(eval(self.__display["text"]))
  46         except: self.__display["text"] = "Error"
  47 
  48     def _clear_display(self): self.__display["text"] = ""
  49 
  50     def mainloop(self): self.__root.mainloop()
  51 
  52 
  53 if __name__ == "__main__":
  54     c = Calculator()
  55     c.mainloop()

---

CategoryProgetti

CookBook/Tkinter (last edited 2008-07-06 20:58:53 by gennaro)