热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python手记(9)

本博客所有内容是原创,未经书面许可,严禁任何形式的转http:blog.csdn.netu010255642tab#!usrbinenvpython#

 

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

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 tabsdef rotate_book(self, button, notebook):notebook.set_tab_pos((notebook.get_tab_pos()+1) %4)
# Add/Remove the page tabs and the bordersdef tabsborder_book(self, button, notebook):tval = Falsebval = Falseif self.show_tabs == False:tval = Trueif self.show_border == False:bval = Truenotebook.set_show_tabs(tval)self.show_tabs = tvalnotebook.set_show_border(bval)self.show_border = bval# Remove a page from the notebookdef 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 Falsedef __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 tabsnotebook = gtk.Notebook()notebook.set_tab_pos(gtk.POS_TOP)table.attach(notebook, 0,6,0,1)notebook.show()self.show_tabs = Trueself.show_border = True# Let’s append a bunch of pages to the notebookfor 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 spotcheckbutton = 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 notebookfor 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 buttonsbutton = 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 0if __name__ == "__main__":NotebookExample()main()

 

 

menu

 

#!/usr/bin/env python# example itemfactory.pyimport pygtk
pygtk.require(’2.0’)
import gtkclass ItemFactoryExample:
# Obligatory basic callbackdef 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 -> ""# "" -> ""# "" -> create a title item# "" -> create a simple item# "" -> create a check item# "" -> create a toggle item# "" -> create a radio item# -> path of a radio item to link against# "" -> create a separator# "" -> create an item to hold sub items (optional)# "" -> create a right justified branchdef 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, "

", accel_group)# This method generates the menu items. Pass to the item factory# the list of menu itemsitem_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 destructionself.item_factory = item_factory# Finally, return the actual menu bar created by the item factory.return item_factory.get_widget("
")def __init__(self):self.menu_items = (( "/_File", None, None, 0, "" ),( "/File/_New", "N", self.print_hello, 0, None ),( "/File/_Open", "O", self.print_hello, 0, None ),( "/File/_Save", "S", self.print_hello, 0, None ),( "/File/Save _As", None, None, 0, None ),( "/File/sep1", None, None, 0, "" ),( "/File/Quit", "Q", gtk.main_quit, 0, None ),( "/_Options", None, None, 0, "" ),( "/Options/Test", None, None, 0, None ),( "/_Help", None, None, 0, "" ),( "/_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 0if __name__ == "__main__":ItemFactoryExample()main()


 

 

#!/usr/bin/env python# example menu.pyimport pygtk
pygtk.require('2.0')
import gtkclass MenuExample:def __init__(self):# create a new windowwindow = 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 appmenu = 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 selectedmenu_items.connect("activate", self.menuitem_response, buf)# Show the widgetmenu_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 appmenu = 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 selectedmenu_items.connect("activate", self.menuitem_response, buf)# Show the widgetmenu_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 windowmenu_bar = gtk.MenuBar()vbox.pack_start(menu_bar, False, False, 2)menu_bar.show()# Create a button to which to attach menu as a popupbutton = 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 selecteddef menuitem_response(self, widget, string):print "%s" % stringdef main():gtk.main()return 0if __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.pyimport pygtk
pygtk.require('2.0')
import gtkclass BasicTreeViewExample:# close the window and quitdef delete_event(self, widget, event, data=None):gtk.main_quit()return Falsedef __init__(self):# Create a new windowself.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 modelself.treestore = gtk.TreeStore(str)# we'll add some data now - 4 rows with 3 child rows eachfor 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 treestoreself.treeview = gtk.TreeView(self.treestore)# create the TreeViewColumn to display the dataself.tvcolumn = gtk.TreeViewColumn('Column 0')# add tvcolumn to treeviewself.treeview.append_column(self.tvcolumn)# create a CellRendererText to render the dataself.cell = gtk.CellRendererText()# add the cell to the tvcolumn and allow it to expandself.tvcolumn.pack_start(self.cell, True)# set the cell "text" attribute to column 0 - retrieve text# from that column in treestoreself.tvcolumn.add_attribute(self.cell, 'text', 0)# make it searchableself.treeview.set_search_column(0)# Allow sorting on the columnself.tvcolumn.set_sort_column_id(0)# Allow drag and drop reordering of rowsself.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脚本了。

 

 

 





推荐阅读
author-avatar
走过滴岁月688
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有