#!/usr/bin/python #list is a mutable sequence data type list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists #------------------------------------------------------------------ list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] #------------------------------------------------------------------ #Updating Lists list = ['physics', 'chemistry', 1997, 2000]; print "Value available at index 2 : " print list[2]; list[2] = 2001; print "New value available at index 2 : " print list[2]; #------------------------------------------------------------------ colors = ["red", "green", "burnt sienna", "blue"] print colors print colors[0:2] #------------------------------------------------------------------ colors = ["red", "green", "burnt sienna", "blue"] colors[0] = "burgundy" colors[3] = "electric indigo" print colors #------------------------------------------------------------------ animals = [] animals.append("lion") animals.append("tiger") animals.append("frumious Bandersnatch") print animals #------------------------------------------------------------------ groceries = "eggs, spam, pop rocks, cheese" groceryList = groceries.split(", ") print groceryList #------------------------------------------------------------------ zero = 1 one = 2 two = [5, 4, 3, 2, 1, 0] three = "I love Python!" four = [["P", "y", "t", "h", "o", "n"],["i", "s"],["h", "a", "r","d"]] five = {"happy":"birthday"} six = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} days = ("Fri", "Sat", "Sun") x, y, seven = days print "zero: {}".format(zero == 0) print "one: {}".format(one > 22) print "two: {}".format(len(two) == 5) print "three: {}".format(three[2] == "Python!") print "four: {}".format(four[0][5] == 'n' and four[0][0] == "P" and four[2][1] == "u") print "five: {}".format(five.get("fish") == "chips") print "five: {}".format(len(five) == 3) print "six: {}".format(len(six & {2,5,7}) == 2) print "seven: {}".format(seven == "Wed") #------------------------------------------------------------------ num = [0, 2, 5, 4, 6, 7] print num[0] # 0 print num[2:] # [5, 4, 6, 7] print len(num) # 6 print num + [8, 9] # [0, 2, 5, 4, 6, 7, 8, 9] #------------------------------------------------------------------ numbers = [4, 3, 6, 1, 2, 0, 5 ] print numbers # [4, 3, 6, 1, 2, 0, 5] numbers.sort() print numbers # [0, 1, 2, 3, 4, 5, 6] numbers.reverse() print numbers # [5, 4, 3, 2, 1, 0] #------------------------------------------------------------------ numbers = [0, 0, 2, 3, 3, 3, 3] print "zero is here ", numbers.count(0), "times" # zero is here 2 times print "one is here ", numbers.count(1), "times" # one is here 0 times print "two is here ", numbers.count(2), "time" # two is here 1 time print "three is here ", numbers.count(3), "times" # three is here 4 times #------------------------------------------------------------------ names = [] names.append("Frank") names.append("Alexis") names.append("Erika") names.append("Ludmila") print names # ['Frank', 'Alexis', 'Erika', 'Ludmila'] names.insert(0, "Adriana") print names # ['Adriana', 'Frank', 'Alexis', 'Erika', 'Ludmila'] names.remove("Frank") names.remove("Alexis") del names[1] print names # ['Adriana', 'Ludmila'] del names[0] print names # ['Ludmila'] #------------------------------------------------------------------ first = [1, 2, 3] second = [4, 5, 6] first.extend(second) print first # [1, 2, 3, 4, 5, 6] first[0] = 11 first[1] = 22 first[2] = 33 print first # [11, 22, 33, 4, 5, 6] print first.pop(5) # 6 print first # [11, 22, 33, 4, 5] #------------------------------------------------------------------ numbers = [0, 1, 2, 3, 3, 4, 5] print numbers.index(1) # 1 print numbers.index(3) # 3 #------------------------------------------------------------------ set1 = set(['a', 'b', 'c', 'c', 'd']) set2 = set(['a', 'b', 'x', 'y', 'z']) print "set1: " , set1 # set1: set(['a', 'c', 'b', 'd']) print "set2: " , set2 # set2: set(['a', 'x', 'b', 'y', 'z']) print "intersection: ", set1 & set2 # intersection: set(['a', 'b']) print "union: ", set1 | set2 # union: set(['a', 'c', 'b', 'd', 'y', 'x', 'z']) print "difference: ", set1 - set2 # difference: set(['c', 'd']) print "symmetric difference: ", set1 ^ set2 # symmetric difference: set(['c', 'd', 'y', 'x', 'z']) #------------------------------------------------------------------ set1 = set([1, 2]) set1.add(3) set1.add(4) set2 = set([1, 2, 3, 4, 6, 7, 8]) set2.remove(8) print set1 # set([1, 2, 3, 4]) print set2 # set([1, 2, 3, 4, 6, 7]) print "Is set1 subset of set2 ? : ", set1.issubset(set2) # Is set1 subset of set2 ? : True print "Is set1 superset of set2 ? : ", set1.issuperset(set2) # Is set1 superset of set2 ? : False set1.clear() print set1 # set([]) #------------------------------------------------------------------ words = { 'girl': 'Maedchen', 'house': 'Haus', 'death': 'Tod' } print words['house'] # Haus print words.keys() # ['house', 'girl', 'death'] print words.values() # ['Haus', 'Maedchen', 'Tod'] print words.items() # [('house', 'Haus'), ('girl', 'Maedchen'), ('death', 'Tod')] print words.pop('girl') # Maedchen print words # {'house': 'Haus', 'death': 'Tod'} words.clear() print words # {} #------------------------------------------------------------------ a = [] b = list() print a == b # True print list((1, 2, 3)) # [1, 2, 3] print list("ZetCode") # ['Z', 'e', 't', 'C', 'o', 'd', 'e'] print list(['Ruby', 'Python', 'Perl']) # ['Ruby', 'Python', 'Perl'] #------------------------------------------------------------------ n1 = [1, 2, 3, 4, 5] n2 = [3, 4, 5, 6, 7] print n1 == n2 # False print n1 + n2 # [1, 2, 3, 4, 5, 3, 4, 5, 6, 7] print n1 * 3 # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5] print 2 in n1 # True print 2 in n2 # False #------------------------------------------------------------------ n = [1, 2, 3, 4, 5, 6, 7, 8] print "There are %d items" % len(n) # There are 8 items print "Maximum is %d" % max(n) # Maximum is 8 print "Minimum is %d" % min(n) # Minimum is 1 print "The sum of values is %d" % sum(n) # The sum of values is 36 #------------------------------------------------------------------ langs = list() langs.append("Python") langs.append("Perl") print langs # ['Python', 'Perl'] langs.insert(0, "PHP") langs.insert(2, "Lua") print langs # ['PHP', 'Python', 'Lua', 'Perl'] langs.extend(("JavaScript", "ActionScript")) print langs # ['PHP', 'Python', 'Lua', 'Perl', 'JavaScript', 'ActionScript'] #------------------------------------------------------------------ #IndexError, TypeError n = [1, 2, 3, 4, 5] try: n[0] = 10 n[6] = 60 except IndexError, e: print e # list assignment index out of range #------------------------------------------------------------------ # TypeError n = [1, 2, 3, 4, 5] try: print n[1] print n['2'] except TypeError, e: print "Error in file %s" % __file__ print "Message: %s" % e # Message: list indices must be integers, not str #------------------------------------------------------------------ #Removing elements langs = ["Python", "Ruby", "Perl", "Lua", "JavaScript"] print langs # ['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript'] langs.pop(3) langs.pop() print langs # ['Python', 'Ruby', 'Perl'] langs.remove("Ruby") print langs # ['Python', 'Perl'] #------------------------------------------------------------------ #Modifying elements langs = ["Python", "Ruby", "Perl"] langs.pop(2) langs.insert(2, "PHP") print langs # ['Python', 'Ruby', 'PHP'] langs[2] = "Perl" print langs # ['Python', 'Ruby', 'Perl'] #------------------------------------------------------------------ #Indexing list elements n = [1, 2, 3, 4, 5, 6, 7, 8] print n[0] # 1 print n[-1] # 8 print n[-2] # 7 print n[3] # 4 print n[5] # 6 #------------------------------------------------------------------ n = [1, 2, 3, 4, 1, 2, 3, 1, 2] print n.index(1) # 0 print n.index(2) # 1 print n.index(1, 1) # 4 print n.index(2, 2) # 5 print n.index(1, 2, 5) # 4 print n.index(3, 4, 8) # 6 #------------------------------------------------------------------ #Slicing n = [1, 2, 3, 4, 5, 6, 7, 8] print n[1:5] # [2, 3, 4, 5] print n[:5] # [1, 2, 3, 4, 5] print n[1:] # [2, 3, 4, 5, 6, 7, 8] print n[:] # [1, 2, 3, 4, 5, 6, 7, 8] #------------------------------------------------------------------ basket = { 'oranges': 12, 'pears': 5, 'apples': 4 } basket['bananas'] = 5 print basket # {'bananas': 5, 'pears': 5, 'oranges': 12, 'apples': 4} print "There are %d various items in the basket" % len(basket) # There are 4 various items in the basket print basket['apples'] # 4 basket['apples'] = 8 print basket['apples'] # 8 print basket.get('oranges', 'undefined') # 8 print basket.get('cherries', 'undefined') # undefined #------------------------------------------------------------------ domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary", "us": "United States", "no": "Norway" } for key in domains: print key for k in domains: print domains[k] for k, v in domains.items(): print ": ".join((k, v)) #------------------------------------------------------------------ items = { "coins": 7, "pens": 3, "cups": 2, "bags": 1, "bottles": 4, "books": 5 } kitems = items.keys() kitems.sort() for k in kitems: print ": ".join((k, str(items[k]))) # bags: 1 books: 5 bottles: 4 coins: 7 cups: 2 pens: 3 #------------------------------------------------------------------ dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Name']: ", dict['Name']; print "dict['Age']: ", dict['Age'];
article
Sunday, May 29, 2016
Python List Example code
Python List Example code
Python Date and time Example code
Python Date and time Example code
#!/usr/bin/python import time; # This is required to include time module. ticks = time.time() print "Number of ticks since 12:00am, January 1, 1970:", ticks localtime = time.localtime(time.time()) print "Local current time :", localtime #formated time localtime = time.asctime( time.localtime(time.time()) ) print ("Local current time :", localtime) #Getting calendar for a month import calendar cal = calendar.month(2016, 2) print ("Here is the calendar:") print (cal)
Python Class Example code
Python Class Example code
class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print ("Total Employee %d" % Employee.empCount) def displayEmployee(self): print ("Name : ", self.name, ", Salary: ", self.salary) #This would create first object of Employee class" emp1 = Employee("Zara", 2000) #This would create second object of Employee class" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print ("Total Employee %d" % Employee.empCount) #-------------------------------------------------------------- class Square: def __init__(self, x): self.a = x def area(self): print self.a * self.a sq = Square(12) sq.area()
Saturday, May 28, 2016
wxpython widgets wx.StaticText
wxpython widgets wx.StaticText
A wx.StaticText widget displays one or more lines of read-only text.
A wx.StaticText widget displays one or more lines of read-only text.
import wx class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): txt1 = '''I'm giving up the ghost of love in the shadows cast on devotion She is the one that I adore creed of my silent suffocation Break this bittersweet spell on me lost in the arms of destiny''' txt2 = '''There is something in the way You're always somewhere else Feelings have deserted me To a point of no return I don't believe in God But I pray for you''' pnl = wx.Panel(self) #create panel vbox = wx.BoxSizer(wx.VERTICAL) #This is a string to be shown in the wx.StaticText widget. #wx.StaticText(variable panel,lable,style) st1 = wx.StaticText(pnl, label=txt1, style=wx.ALIGN_CENTRE) st2 = wx.StaticText(pnl, label=txt2, style=wx.ALIGN_CENTRE) vbox.Add(st1, flag=wx.ALL, border=5) vbox.Add(st2, flag=wx.ALL, border=5) pnl.SetSizer(vbox) self.SetSize((250, 260)) self.SetTitle('Bittersweet') self.Centre() self.Show(True) def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython widgets wx.StaticLine
wxpython widgets wx.StaticLine
This widget displays a simple line on the window. It can be horizontal or vertical.
This widget displays a simple line on the window. It can be horizontal or vertical.
import wx class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() #call function def InitUI(self): def InitUI(self): pnl = wx.Panel(self) #create panel font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD) heading = wx.StaticText(self, label='The Central Europe', pos=(130, 15)) heading.SetFont(font) wx.StaticLine(self, pos=(25, 50), size=(300,1)) wx.StaticText(self, label='Slovakia', pos=(25, 80)) wx.StaticText(self, label='Hungary', pos=(25, 100)) wx.StaticText(self, label='Poland', pos=(25, 120)) wx.StaticText(self, label='Czech Republic', pos=(25, 140)) wx.StaticText(self, label='Germany', pos=(25, 160)) wx.StaticText(self, label='Slovenia', pos=(25, 180)) wx.StaticText(self, label='Austria', pos=(25, 200)) wx.StaticText(self, label='Switzerland', pos=(25, 220)) wx.StaticText(self, label='5 445 000', pos=(250, 80)) wx.StaticText(self, label='10 014 000', pos=(250, 100)) wx.StaticText(self, label='38 186 000', pos=(250, 120)) wx.StaticText(self, label='10 562 000', pos=(250, 140)) wx.StaticText(self, label='81 799 000', pos=(250, 160)) wx.StaticText(self, label='2 050 000', pos=(250, 180)) wx.StaticText(self, label='8 414 000', pos=(250, 200)) wx.StaticText(self, label='7 866 000', pos=(250, 220)) wx.StaticLine(self, pos=(25, 260), size=(300,1)) tsum = wx.StaticText(self, label='164 336 000', pos=(240, 280)) sum_font = tsum.GetFont() sum_font.SetWeight(wx.BOLD) tsum.SetFont(sum_font) btn = wx.Button(self, label='Close', pos=(140, 310)) btn.Bind(wx.EVT_BUTTON, self.OnClose) self.SetSize((360, 380)) self.SetTitle('wx.StaticLine')#form panel title self.Centre() self.Show(True) def OnClose(self, e): self.Close(True) def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython widgets wx.ToggleButton
wxpython widgets wx.ToggleButton
wx.ToggleButton is a button that has two states: pressed and not pressed.
wx.ToggleButton is a button that has two states: pressed and not pressed.
import wx class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): #wx.ToggleButton(panel,label,position) pnl = wx.Panel(self) #set panel self.col = wx.Colour(0, 0, 0) rtb = wx.ToggleButton(pnl, label='red', pos=(20, 25)) gtb = wx.ToggleButton(pnl, label='green', pos=(20, 60)) btb = wx.ToggleButton(pnl, label='blue', pos=(20, 100)) self.cpnl = wx.Panel(pnl, pos=(150, 20), size=(110, 110)) self.cpnl.SetBackgroundColour(self.col) #The ToggleRed() event handler is called, when click on the rtb toggle button. rtb.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleRed) #bind button, set function gtb.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleGreen) btb.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleBlue) self.SetSize((300, 200))#form panel size self.SetTitle('Toggle buttons') #form panel title self.Centre()#panel center self.Show(True) def ToggleRed(self, e): obj = e.GetEventObject() isPressed = obj.GetValue() green = self.col.Green() blue = self.col.Blue() if isPressed: self.col.Set(255, green, blue) else: self.col.Set(0, green, blue) self.cpnl.SetBackgroundColour(self.col) self.cpnl.Refresh() def ToggleGreen(self, e): obj = e.GetEventObject() isPressed = obj.GetValue() red = self.col.Red() blue = self.col.Blue() if isPressed: self.col.Set(red, 255, blue) else: self.col.Set(red, 0, blue) self.cpnl.SetBackgroundColour(self.col) self.cpnl.Refresh() def ToggleBlue(self, e): obj = e.GetEventObject() isPressed = obj.GetValue() red = self.col.Red() green = self.col.Green() if isPressed: self.col.Set(red, green, 255) else: self.col.Set(red, green, 0) self.cpnl.SetBackgroundColour(self.col) self.cpnl.Refresh() def main(): ex = wx.App() Example(None) #call class Example(wx.Frame): ex.MainLoop() if __name__ == '__main__': main()
wxpython widgets wx.Button
wxpython widgets wx.Button
wx.Button is a simple widget. It contains a text string. It is used to trigger an action.
wxpython widgets wx.Button when click change label value
wx.Button is a simple widget. It contains a text string. It is used to trigger an action.
import wx class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): pnl = wx.Panel(self) cbtn = wx.Button(pnl, label='Close', pos=(20, 30))#pos position #The wx.EVT_BUTTON event is triggered when we click on the button. We specify the event handler for the event. cbtn.Bind(wx.EVT_BUTTON, self.OnClose) #call function def OnClose(self, e): self.SetSize((250, 200)) #set form size self.SetTitle('wx.Button') #set form title self.Centre() #center form self.Show(True) #show form def OnClose(self, e): self.Close(True) #close form def main(): ex = wx.App() Example(None) #call frame class Example(wx.Frame): ex.MainLoop() if __name__ == '__main__': main()
import wx class MyFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent=parent) self.panel = wx.Panel(self) self.label = {} for i in range(5): button = wx.Button( self.panel, -1, label='b' + str(i), pos=(20, 30 * i)) button.Bind(wx.EVT_BUTTON, self.on_button) label = wx.StaticText(self.panel, -1, label='label' + str( i), pos=(120, 30 * i), name='label' + str(i)) self.label[button] = label def on_button(self, event): button = event.GetEventObject() label = self.label[button] label.SetLabel('sss') x = wx.App() y = MyFrame(None).Show() x.MainLoop()
wxpython dialogs custom dialog
wxpython dialogs custom dialog
import wx class ChangeDepthDialog(wx.Dialog): #class ChangeDepthDialog create a custom dialog def __init__(self, *args, **kw): super(ChangeDepthDialog, self).__init__(*args, **kw) # create a custom ChangeDepthDialog dialog self.InitUI() #call function def InitUI(self): self.SetSize((250, 200)) #form size self.SetTitle("Change Color Depth") #form title def InitUI(self): pnl = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) sb = wx.StaticBox(pnl, label='Colors') sbs = wx.StaticBoxSizer(sb, orient=wx.VERTICAL) sbs.Add(wx.RadioButton(pnl, label='256 Colors', style=wx.RB_GROUP)) sbs.Add(wx.RadioButton(pnl, label='16 Colors')) sbs.Add(wx.RadioButton(pnl, label='2 Colors')) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(wx.RadioButton(pnl, label='Custom')) hbox1.Add(wx.TextCtrl(pnl), flag=wx.LEFT, border=5) sbs.Add(hbox1) pnl.SetSizer(sbs) hbox2 = wx.BoxSizer(wx.HORIZONTAL) okButton = wx.Button(self, label='Ok') closeButton = wx.Button(self, label='Close') hbox2.Add(okButton) hbox2.Add(closeButton, flag=wx.LEFT, border=5) vbox.Add(pnl, proportion=1, flag=wx.ALL|wx.EXPAND, border=5) vbox.Add(hbox2, flag=wx.ALIGN_CENTER|wx.TOP|wx.BOTTOM, border=10) self.SetSizer(vbox) okButton.Bind(wx.EVT_BUTTON, self.OnClose) closeButton.Bind(wx.EVT_BUTTON, self.OnClose) def OnClose(self, e): self.Destroy() class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): ID_DEPTH = wx.NewId() tb = self.CreateToolBar() tb.AddLabelTool(id=ID_DEPTH, label='', bitmap=wx.Bitmap('icon_folder.png')) tb.Realize() self.Bind(wx.EVT_TOOL, self.OnChangeDepth, id=ID_DEPTH) self.SetSize((300, 200)) self.SetTitle('Custom dialog') self.Centre() self.Show(True) def OnChangeDepth(self, e): chgdep = ChangeDepthDialog(None, title='Change Color Depth') chgdep.ShowModal() chgdep.Destroy() def main(): ex = wx.App() Example(None) #class Example(wx.Frame): ex.MainLoop() if __name__ == '__main__': main()
wxpython dialogs About dialog box
wxpython dialogs About dialog box
In order to create an about dialog box we must create two objects. A wx.AboutDialogInfo and a wx.AboutBox.
In order to create an about dialog box we must create two objects. A wx.AboutDialogInfo and a wx.AboutBox.
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() #call function def InitUI(self): def InitUI(self): menubar = wx.MenuBar() help = wx.Menu() help.Append(100, '&About') self.Bind(wx.EVT_MENU, self.OnAboutBox, id=100) #bind menu and call function def OnAboutBox(self, e): menubar.Append(help, '&Help') self.SetMenuBar(menubar) self.SetSize((300, 200)) #form size self.SetTitle('About dialog box') #form title self.Centre() #form center self.Show(True) #show form def OnAboutBox(self, e): description = """Neque porro quisquam est qui dolore orem ipsum quia dolor sit amet, consectetur, adipisci ue porro quisquam est qui dolore ipsum quia dolor sit amet, consectetur, adipisci velit.. """ licence = """eque porro quisquam est qui do em ipsum quia dolor sit amet, consectetur, quam est qui dolorem ipsum quia dolor sit amet, consectetur, adipis eque porro quisquam est qui dolorem ipsu uia dolor sit amet, consectetur, adipisci , eque porro quisquam est qui dolorem ipsum ia dolor sit amet, consectet lorem ipsum quia dolor sit amet, consectetur, adi""" #The first thing to do is to create a wx.AboutDialogInfo object. The constructor is empty. #It does not taky any parameters. info = wx.AboutDialogInfo() info.SetIcon(wx.Icon('icon_folder.png', wx.BITMAP_TYPE_PNG)) info.SetName('About dialog box') info.SetVersion('1.0') info.SetDescription(description) info.SetCopyright('(C) 2016 - 2017 tutorial1.101') info.SetWebSite('http://tutorial101.blogspot.com/') info.SetLicence(licence) info.AddDeveloper('Tutorial101') info.AddDocWriter('Tutorial101') info.AddArtist('Tutorial101') info.AddTranslator('Tutorial101') #The next thing to do is to call all necessary methods upon the created wx.AboutDialogInfo object. wx.AboutBox(info) wx.AboutBox(info) def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython dialogs Message dialogs
wxpython dialogs Message dialogs
Message dialogs are used to show messages to the user. They are more flexible than simple message boxes that we saw in the previous example. They are customisable. We can change icons and buttons that will be shown in a dialog.
Message dialogs are used to show messages to the user. They are more flexible than simple message boxes that we saw in the previous example. They are customisable. We can change icons and buttons that will be shown in a dialog.
flag | meaning |
---|---|
wx.OK | show OK button |
wx.CANCEL | show Cancel button |
wx.YES_NO | show Yes, No buttons |
wx.YES_DEFAULT | make Yes button the default |
wx.NO_DEFAULT | make No button the default |
wx.ICON_EXCLAMATION | show an alert icon |
wx.ICON_ERROR | show an error icon |
wx.ICON_HAND | same as wx.ICON_ERROR |
wx.ICON_INFORMATION | show an info icon |
wx.ICON_QUESTION | show a question icon |
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): panel = wx.Panel(self) hbox = wx.BoxSizer() sizer = wx.GridSizer(2, 2, 2, 2) btn1 = wx.Button(panel, label='Info') btn2 = wx.Button(panel, label='Error') btn3 = wx.Button(panel, label='Question') btn4 = wx.Button(panel, label='Alert') sizer.AddMany([btn1, btn2, btn3, btn4]) hbox.Add(sizer, 0, wx.ALL, 15) panel.SetSizer(hbox) btn1.Bind(wx.EVT_BUTTON, self.ShowMessage1) #Bind btn1 and ShowMessage1 function btn2.Bind(wx.EVT_BUTTON, self.ShowMessage2) btn3.Bind(wx.EVT_BUTTON, self.ShowMessage3) btn4.Bind(wx.EVT_BUTTON, self.ShowMessage4) self.SetSize((300, 200)) self.SetTitle('Messages') #form title self.Centre() self.Show(True) def ShowMessage1(self, event): #show function dial = wx.MessageDialog(None, 'Download completed', 'Info', wx.OK) dial.ShowModal() #show the dialog on screen, call the ShowModal() method def ShowMessage2(self, event): dial = wx.MessageDialog(None, 'Error loading file', 'Error', wx.OK | wx.ICON_ERROR) dial.ShowModal() def ShowMessage3(self, event): dial = wx.MessageDialog(None, 'Are you sure to quit?', 'Question', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) dial.ShowModal() def ShowMessage4(self, event): dial = wx.MessageDialog(None, 'Unallowed operation', 'Exclamation', wx.OK | wx.ICON_EXCLAMATION) dial.ShowModal() def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython dialogs wx.MessageBox
wxpython dialogs wx.MessageBox
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): wx.FutureCall(5000, self.ShowMessage) #wx.FutureCall shows a message box after 5 seconds. 5000 milliseconds, self.ShowMessage method self.SetSize((300, 200)) self.SetTitle('Message box') self.Centre() self.Show(True) def ShowMessage(self): wx.MessageBox('Download completed', 'Info', wx.OK | wx.ICON_INFORMATION) def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython Events KeyEvent
wxpython Events KeyEvent
When we press a key on our keyboard, a wx.KeyEvent is generated. This event is sent to the widget that has currently focus.
When we press a key on our keyboard, a wx.KeyEvent is generated. This event is sent to the widget that has currently focus.
import wx class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): #There are three different key handlers,wx.EVT_KEY_DOWN, wx.EVT_KEY_UP, wx.EVT_CHAR pnl = wx.Panel(self) pnl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) pnl.SetFocus() self.SetSize((250, 180)) self.SetTitle('Key event') self.Centre() self.Show(True) def OnKeyDown(self, e): key = e.GetKeyCode() if key == wx.WXK_ESCAPE: # when the Esc key is pressed ret = wx.MessageBox('Are you sure to quit?', 'Question', wx.YES_NO | wx.NO_DEFAULT, self) if ret == wx.YES: self.Close() def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython Events identifiers global ids
wxpython Events identifiers global ids
import wx ID_MENU_NEW = wx.NewId() ID_MENU_OPEN = wx.NewId() ID_MENU_SAVE = wx.NewId() class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.CreateMenuBar() self.CreateStatusBar() self.SetSize((250, 180)) self.SetTitle('Global ids') self.Centre() self.Show(True) def CreateMenuBar(self): mb = wx.MenuBar() fMenu = wx.Menu() fMenu.Append(ID_MENU_NEW, 'New') fMenu.Append(ID_MENU_OPEN, 'Open') fMenu.Append(ID_MENU_SAVE, 'Save') mb.Append(fMenu, '&File') self.SetMenuBar(mb) self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_NEW) self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_OPEN) self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_SAVE) def DisplayMessage(self, e): sb = self.GetStatusBar() eid = e.GetId() if eid == ID_MENU_NEW: msg = 'New menu item selected' elif eid == ID_MENU_OPEN: msg = 'Open menu item selected' elif eid == ID_MENU_SAVE: msg = 'Save menu item selected' sb.SetStatusText(msg) def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython Events Vetoing events
wxpython Events Vetoing events
import wx class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): # Bind() method #Bind(event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.SetTitle('Event veto') self.Centre() self.Show(True) def OnCloseWindow(self, e): dial = wx.MessageDialog(None, 'Are you sure to quit?', 'Question', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) ret = dial.ShowModal() if ret == wx.ID_YES: self.Destroy() else: e.Veto() def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
Friday, May 27, 2016
wxpython Events wx.MoveEvent
wxpython Events wx.MoveEvent
import wx class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): wx.StaticText(self, label='x:', pos=(10,10)) wx.StaticText(self, label='y:', pos=(10,30)) self.st1 = wx.StaticText(self, label='', pos=(30, 10)) self.st2 = wx.StaticText(self, label='', pos=(30, 30)) self.Bind(wx.EVT_MOVE, self.OnMove) #bind the wx.EVT_MOVE event binder to the OnMove() method self.SetSize((250, 180)) self.SetTitle('Move event') self.Centre() self.Show(True) def OnMove(self, e): x, y = e.GetPosition() #call GetPosition() method self.st1.SetLabel(str(x)) self.st2.SetLabel(str(y)) def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython layout wx.GridBagSizer
wxpython layout wx.GridBagSizer
import wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, size=(450, 350)) self.InitUI() self.Centre() self.Show() def InitUI(self): panel = wx.Panel(self) sizer = wx.GridBagSizer(5, 5) text1 = wx.StaticText(panel, label="Java Class") sizer.Add(text1, pos=(0, 0), flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=15) icon = wx.StaticBitmap(panel, bitmap=wx.Bitmap('open.png')) sizer.Add(icon, pos=(0, 4), flag=wx.TOP|wx.RIGHT|wx.ALIGN_RIGHT, border=5) line = wx.StaticLine(panel) sizer.Add(line, pos=(1, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=10) text2 = wx.StaticText(panel, label="Name") sizer.Add(text2, pos=(2, 0), flag=wx.LEFT, border=10) tc1 = wx.TextCtrl(panel) sizer.Add(tc1, pos=(2, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND) text3 = wx.StaticText(panel, label="Package") sizer.Add(text3, pos=(3, 0), flag=wx.LEFT|wx.TOP, border=10) tc2 = wx.TextCtrl(panel) sizer.Add(tc2, pos=(3, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND, border=5) button1 = wx.Button(panel, label="Browse...") sizer.Add(button1, pos=(3, 4), flag=wx.TOP|wx.RIGHT, border=5) text4 = wx.StaticText(panel, label="Extends") sizer.Add(text4, pos=(4, 0), flag=wx.TOP|wx.LEFT, border=10) combo = wx.ComboBox(panel) sizer.Add(combo, pos=(4, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND, border=5) button2 = wx.Button(panel, label="Browse...") sizer.Add(button2, pos=(4, 4), flag=wx.TOP|wx.RIGHT, border=5) sb = wx.StaticBox(panel, label="Optional Attributes") boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL) boxsizer.Add(wx.CheckBox(panel, label="Public"), flag=wx.LEFT|wx.TOP, border=5) boxsizer.Add(wx.CheckBox(panel, label="Generate Default Constructor"), flag=wx.LEFT, border=5) boxsizer.Add(wx.CheckBox(panel, label="Generate Main Method"), flag=wx.LEFT|wx.BOTTOM, border=5) sizer.Add(boxsizer, pos=(5, 0), span=(1, 5), flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT , border=10) button3 = wx.Button(panel, label='Help') sizer.Add(button3, pos=(7, 0), flag=wx.LEFT, border=10) button4 = wx.Button(panel, label="Ok") sizer.Add(button4, pos=(7, 3)) button5 = wx.Button(panel, label="Cancel") sizer.Add(button5, pos=(7, 4), span=(1, 1), flag=wx.BOTTOM|wx.RIGHT, border=5) sizer.AddGrowableCol(2) panel.SetSizer(sizer) if __name__ == '__main__': app = wx.App() Example(None, title="Create Java Class") app.MainLoop()
wxpython layout wx.FlexGridSizer
wxpython layout wx.FlexGridSizer
wx.GridSizer cells are of the same size
wx.GridSizer cells are of the same size
import wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, size=(300, 250)) self.InitUI() self.Centre() self.Show() def InitUI(self): panel = wx.Panel(self) hbox = wx.BoxSizer(wx.HORIZONTAL) fgs = wx.FlexGridSizer(3, 2, 9, 25) #wx.FlexGridSizer(int rows=1, int cols=0, int vgap=0, int hgap=0) title = wx.StaticText(panel, label="Title") author = wx.StaticText(panel, label="Author") review = wx.StaticText(panel, label="Review") tc1 = wx.TextCtrl(panel) tc2 = wx.TextCtrl(panel) tc3 = wx.TextCtrl(panel, style=wx.TE_MULTILINE) fgs.AddMany([(title), (tc1, 1, wx.EXPAND), (author), (tc2, 1, wx.EXPAND), (review, 1, wx.EXPAND), (tc3, 1, wx.EXPAND)]) fgs.AddGrowableRow(2, 1) fgs.AddGrowableCol(1, 1) hbox.Add(fgs, proportion=1, flag=wx.ALL|wx.EXPAND, border=15) panel.SetSizer(hbox) if __name__ == '__main__': app = wx.App() Example(None, title='Review') app.MainLoop()
wxpython layout GoToClass
wxpython layout GoToClass
import wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, size=(390, 350)) self.InitUI() self.Centre() self.Show() def InitUI(self): panel = wx.Panel(self) font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(9) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) st1 = wx.StaticText(panel, label='Class Name') st1.SetFont(font) hbox1.Add(st1, flag=wx.RIGHT, border=8) tc = wx.TextCtrl(panel) hbox1.Add(tc, proportion=1) vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10) vbox.Add((-1, 10)) hbox2 = wx.BoxSizer(wx.HORIZONTAL) st2 = wx.StaticText(panel, label='Matching Classes') st2.SetFont(font) hbox2.Add(st2) vbox.Add(hbox2, flag=wx.LEFT | wx.TOP, border=10) vbox.Add((-1, 10)) hbox3 = wx.BoxSizer(wx.HORIZONTAL) tc2 = wx.TextCtrl(panel, style=wx.TE_MULTILINE) hbox3.Add(tc2, proportion=1, flag=wx.EXPAND) vbox.Add(hbox3, proportion=1, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=10) vbox.Add((-1, 25)) hbox4 = wx.BoxSizer(wx.HORIZONTAL) cb1 = wx.CheckBox(panel, label='Case Sensitive') cb1.SetFont(font) hbox4.Add(cb1) cb2 = wx.CheckBox(panel, label='Nested Classes') cb2.SetFont(font) hbox4.Add(cb2, flag=wx.LEFT, border=10) cb3 = wx.CheckBox(panel, label='Non-Project classes') cb3.SetFont(font) hbox4.Add(cb3, flag=wx.LEFT, border=10) vbox.Add(hbox4, flag=wx.LEFT, border=10) vbox.Add((-1, 25)) hbox5 = wx.BoxSizer(wx.HORIZONTAL) btn1 = wx.Button(panel, label='Ok', size=(70, 30)) hbox5.Add(btn1) btn2 = wx.Button(panel, label='Close', size=(70, 30)) hbox5.Add(btn2, flag=wx.LEFT|wx.BOTTOM, border=5) vbox.Add(hbox5, flag=wx.ALIGN_RIGHT|wx.RIGHT, border=10) panel.SetSizer(vbox) if __name__ == '__main__': app = wx.App() Example(None, title='Go To Class') app.MainLoop()
wxpython simple Toolbars example
wxpython simple Toolbars example
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): toolbar = self.CreateToolBar() #call CreateToolBar() method qtool = toolbar.AddLabelTool(wx.ID_ANY, 'Quit', wx.Bitmap('img/close.jpg')) toolbar.Realize() self.Bind(wx.EVT_TOOL, self.OnQuit, qtool) #To handle toolbar events, use the wx.EVT_TOOL event binder self.SetSize((250, 200)) self.SetTitle('Simple toolbar') self.Centre() self.Show(True) def OnQuit(self, e): self.Close() def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxpython Context menu right click example
wxpython Context menu right click example
import wx class MyPopupMenu(wx.Menu): def __init__(self, parent): super(MyPopupMenu, self).__init__() self.parent = parent mmi = wx.MenuItem(self, wx.NewId(), 'Minimize') self.AppendItem(mmi) self.Bind(wx.EVT_MENU, self.OnMinimize, mmi) cmi = wx.MenuItem(self, wx.NewId(), 'Close') self.AppendItem(cmi) self.Bind(wx.EVT_MENU, self.OnClose, cmi) def OnMinimize(self, e): self.parent.Iconize() def OnClose(self, e): self.parent.Close() class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): #If right click on the frame, call the OnRightDown() method self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.SetSize((250, 200)) self.SetTitle('Context menu') self.Centre() self.Show(True) def OnRightDown(self, e): self.PopupMenu(MyPopupMenu(self), e.GetPosition()) #call MyPopupMenu class # PopupMenu() method shows the context menu, GetPosition() The context menus appear at the point of the mouse cursor def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
Subscribe to:
Posts (Atom)