python手记(9)

 

本博客所有内容是原创,未经书面许可,严禁任何形式的转

http://blog.csdn.net/u010255642

 

tab

 

#!/usr/bin/env python
# example notebook.py
import pygtk
pygtk.require('2.0')
import gtk
class NotebookExample:
# This method rotates the position of the tabs
	def rotate_book(self, button, notebook):
		notebook.set_tab_pos((notebook.get_tab_pos()+1) %4)
# Add/Remove the page tabs and the borders
	def tabsborder_book(self, button, notebook):
		tval = False
		bval = False
		if self.show_tabs == False:
			tval = True
		if self.show_border == False:
			bval = True
		notebook.set_show_tabs(tval)
		self.show_tabs = tval
		notebook.set_show_border(bval)
		self.show_border = bval

# Remove a page from the notebook
	def remove_book(self, button, notebook):
		page = notebook.get_current_page()
		notebook.remove_page(page)
		# Need to refresh the widget --
		# This forces the widget to redraw itself.
		notebook.queue_draw_area(0,0,-1,-1)

	def delete(self, widget, event=None):
		gtk.main_quit()
		return False

	def __init__(self):
		window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		window.connect("delete_event", self.delete)
		window.set_border_width(10)

		table = gtk.Table(3,6,False)
		window.add(table)

		# Create a new notebook, place the position of the tabs
		notebook = gtk.Notebook()
		notebook.set_tab_pos(gtk.POS_TOP)
		table.attach(notebook, 0,6,0,1)
		notebook.show()
		self.show_tabs = True
		self.show_border = True
		# Let’s append a bunch of pages to the notebook
		for i in range(5):
			bufferf = "Append Frame %d" % (i+1)
			bufferl = "Page %d" % (i+1)

			frame = gtk.Frame(bufferf)
			frame.set_border_width(10)
			frame.set_size_request(100, 75)
			frame.show()

			label = gtk.Label(bufferf)
			frame.add(label)
			label.show()

			label = gtk.Label(bufferl)
			notebook.append_page(frame, label)

			# Now let’s add a page to a specific spot
		checkbutton = gtk.CheckButton("Check me please!")
		checkbutton.set_size_request(100, 75)
		checkbutton.show ()

		label = gtk.Label("Add page")
		notebook.insert_page(checkbutton, label, 2)

	# Now finally let’s prepend pages to the notebook
		for i in range(5):
			bufferf = "Prepend Frame %d" % (i+1)
			bufferl = "PPage %d" % (i+1)

			frame = gtk.Frame(bufferf)
			frame.set_border_width(10)
			frame.set_size_request(100, 75)
			frame.show()

			label = gtk.Label(bufferf)
			frame.add(label)
			label.show()

			label = gtk.Label(bufferl)
			notebook.prepend_page(frame, label)

		# Set what page to start at (page 4)
		notebook.set_current_page(3)

		# Create a bunch of buttons
		button = gtk.Button("close")
		button.connect("clicked", self.delete)
		table.attach(button, 0,1,1,2)
		button.show()
		button = gtk.Button("next page")
		button.connect("clicked", lambda w: notebook.next_page())
		table.attach(button, 1,2,1,2)
		button.show()

		button = gtk.Button("prev page")
		button.connect("clicked", lambda w: notebook.prev_page())
		table.attach(button, 2,3,1,2)
		button.show()

		button = gtk.Button("tab position")
		button.connect("clicked", self.rotate_book, notebook)
		table.attach(button, 3,4,1,2)
		button.show()

		button = gtk.Button("tabs/border on/off")
		button.connect("clicked", self.tabsborder_book, notebook)
		table.attach(button, 4,5,1,2)
		button.show()

		button = gtk.Button("remove page")
		button.connect("clicked", self.remove_book, notebook)
		table.attach(button, 5,6,1,2)
		button.show()

		table.show()
		window.show()

def main():
	gtk.main()
	return 0

if __name__ == "__main__":
	NotebookExample()
	main()

 

 

menu

 

#!/usr/bin/env python

# example itemfactory.py

import pygtk
pygtk.require(’2.0’)
import gtk

class ItemFactoryExample:
# Obligatory basic callback
	def print_hello(self, w, data):
		print "Hello, World!"

		# This is the ItemFactoryEntry structure used to generate new menus.
		# Item 1: The menu path. The letter after the underscore indicates an
		# accelerator key once the menu is open.
		# Item 2: The accelerator key for the entry
		# Item 3: The callback.
		# Item 4: The callback action. This changes the parameters with
		# which the callback is called. The default is 0.
		# Item 5: The item type, used to define what kind of an item it is.
		# Here are the possible values:

		# NULL -> "<Item>"
		# "" -> "<Item>"
		# "<Title>" -> create a title item
		# "<Item>" -> create a simple item
		# "<CheckItem>" -> create a check item
		# "<ToggleItem>" -> create a toggle item
		# "<RadioItem>" -> create a radio item
		# <path> -> path of a radio item to link against
		# "<Separator>" -> create a separator
		# "<Branch>" -> create an item to hold sub items (optional)
		# "<LastBranch>" -> create a right justified branch

	def get_main_menu(self, window):
		accel_group = gtk.AccelGroup()

		# This function initializes the item factory.
		# Param 1: The type of menu - can be MenuBar, Menu,
		# or OptionMenu.
		# Param 2: The path of the menu.
		# Param 3: A reference to an AccelGroup. The item factory sets up
		# the accelerator table while generating menus.
		item_factory = gtk.ItemFactory(gtk.MenuBar, "<main>", accel_group)

		# This method generates the menu items. Pass to the item factory
		# the list of menu items
		item_factory.create_items(self.menu_items)

		# Attach the new accelerator group to the window.
		window.add_accel_group(accel_group)

		# need to keep a reference to item_factory to prevent its destruction
		self.item_factory = item_factory
		# Finally, return the actual menu bar created by the item factory.
		return item_factory.get_widget("<main>")

	def __init__(self):
		self.menu_items = (
		( "/_File", None, None, 0, "<Branch>" ),
		( "/File/_New", "<control>N", self.print_hello, 0, None ),
		( "/File/_Open", "<control>O", self.print_hello, 0, None ),
		( "/File/_Save", "<control>S", self.print_hello, 0, None ),
		( "/File/Save _As", None, None, 0, None ),
		( "/File/sep1", None, None, 0, "<Separator>" ),
		( "/File/Quit", "<control>Q", gtk.main_quit, 0, None ),
		( "/_Options", None, None, 0, "<Branch>" ),
		( "/Options/Test", None, None, 0, None ),
		( "/_Help", None, None, 0, "<LastBranch>" ),
		( "/_Help/About", None, None, 0, None ),
		)
		window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		window.connect("destroy", lambda w: gtk.main_quit(), "WM destroy")
		window.set_title("Item Factory")
		window.set_size_request(300, 200)

		main_vbox = gtk.VBox(False, 1)
		main_vbox.set_border_width(1)
		window.add(main_vbox)
		main_vbox.show()

		menubar = self.get_main_menu(window)

		main_vbox.pack_start(menubar, False, True, 0)
		menubar.show()
		window.show()

def main():
	gtk.main()
	return 0

if __name__ == "__main__":
	ItemFactoryExample()
	main()


 

 

#!/usr/bin/env python

# example menu.py

import pygtk
pygtk.require('2.0')
import gtk

class MenuExample:
    def __init__(self):
         # create a new window
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_size_request(200, 100)
        window.set_title("GTK Menu Test")
        window.connect("delete_event", lambda w,e: gtk.main_quit())

        # Init the menu-widget, and remember -- never
        # show() the menu widget!!
        # This is the menu that holds the menu items, the one that
        # will pop up when you click on the "Root Menu" in the app
        menu = gtk.Menu()

        # Next we make a little loop that makes three menu-entries for
        # "test-menu". Notice the call to gtk_menu_append. Here we are
        # adding a list of menu items to our menu. Normally, we’d also
        # catch the "clicked" signal on each of the menu items and setup a
        # callback for it, but it’s omitted here to save space.
        for i in range(3):
            # Copy the names to the buf.
            buf = "Test-undermenu - %d" % i

            # Create a new menu-item with a name...
            menu_items = gtk.MenuItem(buf)

            # ...and add it to the menu.
            menu.append(menu_items)

            # Do something interesting when the menuitem is selected
            menu_items.connect("activate", self.menuitem_response, buf)

            # Show the widget
            menu_items.show()

        # This is the root menu, and will be the label
        # displayed on the menu bar. There won’t be a signal handler attached,
        # as it only pops up the rest of the menu when pressed.
        root_menu = gtk.MenuItem("Root Menu")

        root_menu.show()

        # Now we specify that we want our newly created "menu" to be the
        # show() the menu widget!!
        # This is the menu that holds the menu items, the one that
        # will pop up when you click on the "Root Menu" in the app
        menu = gtk.Menu()

        # Next we make a little loop that makes three menu-entries for
        # "test-menu". Notice the call to gtk_menu_append. Here we are
        # adding a list of menu items to our menu. Normally, we’d also
        # catch the "clicked" signal on each of the menu items and setup a
        # callback for it, but it’s omitted here to save space.
        for i in range(3):
            # Copy the names to the buf.
            buf = "Test-undermenu - %d" % i

            # Create a new menu-item with a name...
            menu_items = gtk.MenuItem(buf)

            # ...and add it to the menu.
            menu.append(menu_items)

            # Do something interesting when the menuitem is selected
            menu_items.connect("activate", self.menuitem_response, buf)

            # Show the widget
            menu_items.show()

            # This is the root menu, and will be the label
            # displayed on the menu bar. There won’t be a signal handler attached,
            # as it only pops up the rest of the menu when pressed.
        root_menu = gtk.MenuItem("Root Menu")
        root_menu.show()

# menu for the "root menu"
        root_menu.set_submenu(menu)
        
        # A vbox to put a menu and a button in:
        vbox = gtk.VBox(False, 0)
        window.add(vbox)
        vbox.show()
        
        # Create a menu-bar to hold the menus and add it to our main window
        menu_bar = gtk.MenuBar()
        vbox.pack_start(menu_bar, False, False, 2)
        menu_bar.show()
        
        # Create a button to which to attach menu as a popup
        button = gtk.Button("press me")
        button.connect_object("event", self.button_press, menu)
        vbox.pack_end(button, True, True, 2)
        button.show()
    
        # And finally we append the menu-item to the menu-bar -- this is th         
    
                # Now we specify that we want our newly created "menu" to be the
                # "root" menu-item I have been raving about =)
        menu_bar.append (root_menu)
    
            # always display the window as the last step so it all splashes on
            # the screen at once.
        window.show()

     # Respond to a button-press by posting a menu passed in as widget.
     #
     # Note that the "widget" argument is the menu being posted, NOT
     # the button that was pressed.
    def button_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS:
            widget.popup(None, None, None, event.button, event.time)
        # Tell calling code that we have handled this event the buck
        # stops here.
            return True
        # Tell calling code that we have not handled this event pass it on.
        return False

     # Print a string when a menu item is selected
    def menuitem_response(self, widget, string):
        print "%s" % string

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    MenuExample()
    main()


file_menu = gtk.Menu()

 

将file_item做为子菜单加入到file_menu

file_item.set_submenu(file_menu)
在menubar中加入菜单项

menu_bar.append(child)

比如:
menu_bar.append(file_item)

在menubar中右调整,比如help菜单等,我们使用下面的方法:

menu_item.set_right_justified(right_justified)
=========================
1.使用gtk.Menu()创建新的menu

2.gtk.MenuItem() 创建子菜单项,然后使用append()

3. set_submenu() 将子菜单项加入menu中

4.使用gtk.MenuBar()创建menubar

5.append()加入菜单项

6.设置事件

widget.connect_object("event", handler, menu)

webbrowser-打开浏览器

 

#!/usr/bin/env python
import webbrowser
url='deepfuture.iteye.com'
webbrowser.open_new(url)
url='http://www.google.com.hk/search?hl=zh-CN&newwindow=1&safe=strict&client=aff-cs-360se&hs=kma&q=pygtk+deepfuture&oq=pygtk+deepfuture&aq=f&aqi=&aql=&gs_sm=e&gs_upl=3960l5390l0l5930l11l6l0l0l0l0l0l0ll0l0'
webbrowser.open_new_tab(url)

 

 

TreeStore提供分等级,分层次的数据存储,而ListStore提供表格的数据存储,TreeModelSort提供一个排序的模型,TreeModelFilter提供数据子集。通常有以下几个步骤:

1.创建一个tree model对象,通过ListStore或TreeStore

2.TreeView widget 创建并与tree model关联

3.一个或多个TreeViewColumns被创建并插入到TreeView,每个代表一列

4.对于每个TreeViewColumn,CellRenderers被创建并加入TreeViewColumn

5.设置每个CellRenderer的属性

6.TreeView被插入并显示在Window或ScrolledWindow中

7.响应用户的操作

#!/usr/bin/env python

# example basictreeview.py

import pygtk
pygtk.require('2.0')
import gtk

class BasicTreeViewExample:
    
    # close the window and quit
    def delete_event(self, widget, event, data=None):
        gtk.main_quit()
        return False
    
    def __init__(self):
        # Create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        
        self.window.set_title("Basic TreeView Example")
        
        self.window.set_size_request(200, 200)
        
        self.window.connect("delete_event", self.delete_event)
        
        # create a TreeStore with one string column to use as the model
        self.treestore = gtk.TreeStore(str)
        
        # we'll add some data now - 4 rows with 3 child rows each
        for parent in range(4):
            piter = self.treestore.append(None, ['parent %i' % parent])
            for child in range(3):
                    self.treestore.append(piter, ['child %i of parent %i' %(child, parent)])
        # create the TreeView using treestore
        self.treeview = gtk.TreeView(self.treestore)
        
        # create the TreeViewColumn to display the data
        self.tvcolumn = gtk.TreeViewColumn('Column 0')
        
        # add tvcolumn to treeview
        self.treeview.append_column(self.tvcolumn)
        
        # create a CellRendererText to render the data
        self.cell = gtk.CellRendererText()
        
        # add the cell to the tvcolumn and allow it to expand
        self.tvcolumn.pack_start(self.cell, True)
        
        # set the cell "text" attribute to column 0 - retrieve text
        # from that column in treestore
        self.tvcolumn.add_attribute(self.cell, 'text', 0)
        
        # make it searchable
        self.treeview.set_search_column(0)
        
        # Allow sorting on the column
        self.tvcolumn.set_sort_column_id(0)
        
        # Allow drag and drop reordering of rows
        self.treeview.set_reorderable(True)
        
        self.window.add(self.treeview)
        
        self.window.show_all()
    
def main():
    gtk.main()
    
if __name__ == "__main__":
    tvexample = BasicTreeViewExample()
    main()

 

glade

 

 

import pygtk
pygtk.require("2.0")
import gtk
class startlogin(object):
    def close_app(self):
        gtk.main_quit()
    def exit_app(self):
        gtk.Widget.destroy(self.window)
    def on_startshow_destroy(self, widget,data=None):
        self.close_app()
    def on_exitbutton_clicked(self, widget,data=None):
        self.exit_app()        
    def __init__(self):
        builder = gtk.Builder()
        builder.add_from_file("gladexml\startshow.glade")
        builder.connect_signals(self)
        self.window = builder.get_object("startshow")     
if __name__ == "__main__":
    startlogin = startlogin()
    startlogin.window.show()
    gtk.main()



此外,py在WIN下需要配置环境变量:

假设python的安装路径为c:\python2.6,则修改我的电脑->属性->高级->环境变量->系统变量中的PATH为:

 
(为了在命令行模式下运行 Python命令,需要将python.exe所在的目录附加到PATH这个环境变量中。) 
 
PATH=PATH;c:\python26
上述环境变量设置成功之后,就可以在命令行直接使用python命令。或执行"python *.py"运行python脚本了。

 

 

 



posted @ 2013-06-28 19:55  爱生活,爱编程  阅读(470)  评论(0编辑  收藏  举报