Chapitre VI : Interface graphique
require 'tk'
root = TkRoot.new
root.title = "Calculatrice"
chiffre = TkVariable.new
TkEntry.new( root ) {
pack( "side" => "top" )
textvariable chiffre
}
fr = TkFrame.new( root ) {
pack
}
boutons = [ '7', '8', '9', '-',
'4', '5', '6', '+',
'1', '2', '3', '*',
'0', '.', '=', '/' ]
indice = 0
operande1 = nil
operateur = nil
boutons.each {
|lbl|
TkButton.new( fr ) {
text lbl
pady 10
padx 10
grid ( { 'column' => indice % 4, 'row' => indice / 4 } )
command proc {
# Un chiffre
if ( lbl =~ /[0-9\.]/ ) then
puts "ok"
chiffre.value = chiffre.value + lbl
# Une opération
elsif ( lbl =~ /[-+*\/]/ ) then
# Stockage du nombre en cours
operande1 = chiffre.value.to_f
# Stockage de la dernière opération pour le =
operateur = lbl
chiffre.value = ""
elsif ( lbl == '=' ) then
# Test si une opération a bien eu lieu
if operande1.nil? then
Tk.messageBox(
{
'icon' => 'error',
'type' => 'ok',
'message' => 'Opération impossible',
'title' => 'erreur'
}
) else
# Afficher le résultat
case operateur
when '+'
chiffre.value = operande1 + chiffre.value.to_f
when '-'
chiffre.value = operande1 - chiffre.value.to_f
when '*'
chiffre.value = operande1...