Load and save text file : Button « GUI « Perl

Home
Perl
1.Array
2.CGI
3.Class
4.Data Type
5.Database
6.File
7.GUI
8.Hash
9.Language Basics
10.Network
11.Regular Expression
12.Report
13.Statement
14.String
15.Subroutine
16.System Functions
17.Win32
18.XML
Perl » GUI » Button 
Load and save text file
 

#!/usr/local/bin/perl -w
use Tk;
use strict;

our($filename, $info);

my $mw = MainWindow->new;
# Create necessary widgets
my $f = $mw->Frame->pack(-side => 'top', -fill => 'x');
$f->Label(-text => "Filename:")->pack(-side => 'left', -anchor => 'w');
$f->Entry(-textvariable => \$filename)->
    pack(-side => 'left', -anchor => 'w', -fill => 'x', -expand => 1);
$f->Button(-text => "Exit", -command => sub exit; } )->
    pack(-side => 'right');
$f->Button(-text => "Save", -command => \&save_file)->
    pack(-side => 'right', -anchor => 'e');
$f->Button(-text => "Load", -command => \&load_file)->
    pack(-side => 'right', -anchor => 'e');
$mw->Label(-textvariable => \$info, -relief => 'ridge')->
    pack(-side => 'bottom', -fill => 'x');
my $t = $mw->Scrolled("Text")->pack(-side => 'bottom', 
         -fill => 'both', -expand => 1);

MainLoop;

sub load_file {
    $info = "Loading file '$filename'...";
    $t->delete("1.0""end");
    if (!open(FH, "$filename")) {
       $t->insert("end""ERROR: Could not open $filename\n")
     return
    }
    while (<FH>) { 
         $t->insert("end", $_)
    }
    close (FH);
    $info = "File '$filename' loaded";
}

sub save_file {
    $info = "Saving '$filename'";
    open (FH, ">$filename");
    print FH $t->get("1.0""end");
    $info = "Saved.";
}

   
  
Related examples in the same category
1.Your first Perl/Tk program
2.Adding button (control) to a window
3.Pass subroutine to button and get called when clicking
4.Pass value to a subroutine in button action
5.Set Button action command
6.Link a subroutine with a button action
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.