9.14. File
Selections
The file selection widget is a quick and
simple way to display a File dialog box. It comes complete with Ok, Cancel,
and Help buttons, a great way to cut down on programming time.
To create a new file selection box use:
filesel = GtkFileSelection(title)
|
To set the filename,
for example to bring up a specific directory, or give a default filename,
use this method:
filesel.set_filename(filename)
|
To grab the filename
text that the user has entered or clicked on, use this method:
filename = filesel.get_filename()
|
There are also references to the widgets
contained within the file selection widget. These are the filesel
attributes:
filesel.dir_list
filesel.file_list
filesel.selection_entry
filesel.selection_text
filesel.main_vbox
filesel.ok_button
filesel.cancel_button
filesel.help_button
|
Most likely you will want to use the ok_button,
cancel_button,
and help_button attributes
to connect their widget signals to callbacks.
The filesel.py
example program illustrates the use of the fileselection widget. As you
will see, there is nothing much to creating a file selection widget. While
in this example the Help button appears on the screen, it does nothing
as there is not a signal attached to it. Figure 9.13 shows the resulting
display:

Figure 9.13 File Selection Example
The source code for
filesel.py is:
1 #!/usr/bin/env python
2
3 # example filesel.py
4
5 import gtk
6
7 class FileSelectionExample:
8 # Get the selected filename and print it to the console
9 def file_ok_sel(self, w):
10 print "%s" % self.filew.get_filename()
11
12 def destroy(self, widget):
13 gtk.mainquit()
14
15 def __init__(self):
16 # Create a new file selection widget
17 self.filew = gtk.GtkFileSelection("File selection")
18
19 self.filew.connect("destroy", self.destroy)
20 # Connect the ok_button to file_ok_sel method
21 self.filew.ok_button.connect("clicked", self.file_ok_sel)
22
23 # Connect the cancel_button to destroy the widget
24 self.filew.cancel_button.connect_object("clicked", self.filew.destroy,
25 self.filew)
26
27 # Lets set the filename, as if this were a save dialog,
28 # and we are giving a default filename
29 self.filew.set_filename("penguin.png")
30
31 self.filew.show()
32
33 def main():
34 gtk.mainloop()
35 return 0
36
37 if __name__ == "__main__":
38 FileSelectionExample()
39 main()
|