博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python手记(9)
阅读量:7078 次
发布时间:2019-06-28

本文共 15186 字,大约阅读时间需要 50 分钟。

 

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

 

tab

 

#!/usr/bin/env python# example notebook.pyimport pygtkpygtk.require('2.0')import gtkclass 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 0if __name__ == "__main__":	NotebookExample()	main()

 

 

menu

 

#!/usr/bin/env python# example itemfactory.pyimport pygtkpygtk.require(’2.0’)import gtkclass 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 -> "
" # "" -> "
" # "
" -> 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 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, "
", 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("
") 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 pygtkpygtk.require('2.0')import gtkclass 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" % 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 pythonimport webbrowserurl='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 pygtkpygtk.require('2.0')import gtkclass 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 pygtkpygtk.require("2.0")import gtkclass 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脚本了。

 

 

 

你可能感兴趣的文章
Upgrade Guide
查看>>
HDU2929 Bigger is Better[DP 打印方案 !]
查看>>
Atitit.会员卡(包括银行卡)api的设计
查看>>
jquery.form.js+jquery.validation.js实现表单校验和提交
查看>>
装饰者模式的学习(c#) EF SaveChanges() 报错(转载) C# 四舍五入 保留两位小数(转载) DataGridView样式生成器使用说明 MSSQL如何将查询结果拼接...
查看>>
微信小程序 - 更改button状态
查看>>
Hlacon 之Image ,Region,XLD
查看>>
js和jquery获取父级元素、子级元素、兄弟元素的方法
查看>>
国外程序员整理的 C++ 资源大全
查看>>
Git的杀手级功能之 一 远程仓库
查看>>
7-07. PAT排名汇总(25) (结构体 ZJU_PAT)
查看>>
初探flow.js
查看>>
【Android】Android中如何取消调转界面后EditText默认获取聚焦问题
查看>>
Jvm(45),指令集----类型转换指令
查看>>
前端学习-jQuery-2
查看>>
(轉載)教你怎样快速DIY自己的博客园SKIN
查看>>
SQL Server中关于基数估计如何计算预估行数的一些探讨
查看>>
用bochs调试自己写的系统引导代码
查看>>
svn的基线划分与管理
查看>>
黄连解毒汤治疗月经过多
查看>>