#!/usr/bin/python str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string #------------------------------------------------------------------ str = "this is string example....wow!!!"; print "str.capitalize() : ", str.capitalize() #------------------------------------------------------------------ # This is a comment. #Syntax str.center(width[, fillchar]) width -- This is the total width of the string. fillchar -- This is the filler character. str = "this is string example....wow!!!"; print "str.center(40, 'a') : ", str.center(40, 'a') #------------------------------------------------------------------ #string count #Syntax str.count(sub, start= 0,end=len(string)) str = "this is string example....wow!!!"; sub = "i"; print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40) sub = "wow"; print "str.count(sub) : ", str.count(sub) #------------------------------------------------------------------ #string len str = "this is string example....wow!!!"; print "Length of the string: ", len(str); #------------------------------------------------------------------ myString = "abc" stringLength = len(myString) print stringLength #------------------------------------------------------------------ string1 = "abra" string2 = "cadabra" magicString = string1 + string2 print magicString #------------------------------------------------------------------ myNumber = "2" print myNumber + myNumber #------------------------------------------------------------------ myNumber = "12" print myNumber * 3 #------------------------------------------------------------------ myNumber = "12" print int(myNumber) #------------------------------------------------------------------ phrase = "the surprise is in here somewhere" print phrase.find("surprise") #== output 4 #------------------------------------------------------------------ myStory = "I'm telling you the truth; he spoke nothing but the truth!" print myStory.replace("the truth", "lies") # I'm telling you lies; he spoke nothing but lies! #------------------------------------------------------------------ counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print (counter) print (miles) print (name) #------------------------------------------------------------------ long_string = '''This is a string that spans across multiple lines''' long_string = """This is a new string that spans across two lines""" #------------------------------------------------------------------ string1 = "abra" string2 = "cadabra" magic_string = string1 + string2 print(magic_string) #------------------------------------------------------------------ print("abra"+"ca"+"dabra") #abracadabra print("abra", "ca", "dabra") # abra ca dabra #------------------------------------------------------------------ flavor = "birthday cake" print(flavor[3]) #t print(flavor[0]) #b #------------------------------------------------------------------ flavor = "birthday cake" print(flavor[0:3]) # bir #------------------------------------------------------------------ flavor = "birthday cake" print(flavor[:5]) # birth print(flavor[5:]) # day cake print(flavor[:]) # birthday cake #------------------------------------------------------------------ my_string = "abc" string_length = len(my_string) print(string_length) # 3 #------------------------------------------------------------------ name1 = "Jane" age1 = 12 print name1, age1 #------------------------------------------------------------------ baskets = 16 apples_in_basket = 24 total = baskets * apples_in_basket print "There are total of", total, "apples" #There are total of 384 apples #------------------------------------------------------------------ distance = 0.1 time = 9.87 / 3600 speed = distance / time print "The average speed of" \ " a sprinter is " , speed, "km/h" #The average speed of a sprinter is 36.4741641337 km/h #------------------------------------------------------------------ print "eagle " * 5 # eagle eagle eagle eagle eagle print "eagle " "falcon" # eagle falcon print "eagle " + "and " + "falcon" # eagle and falcon #------------------------------------------------------------------ first = (1, 2, 3) second = (4, 5, 6) print "len(first) : ", len(first) # len(first) : 3 print "max(first) : ", max(first) # max(first) : 3 print "min(first) : ", min(first) # min(first) : 1 print "first + second :", first + second # first + second : (1, 2, 3, 4, 5, 6) print "first * 3 : ", first * 3 # first * 3 : (1, 2, 3, 1, 2, 3, 1, 2, 3) print "1 in first : ", 1 in first # 1 in first : True print "5 not in second : ", 5 not in second # 5 not in second : False #------------------------------------------------------------------ five = (1, 2, 3, 4, 5) print "five[0] : ", five[0] # five[0] : 1 print "five[-1] : ", five[-1] # five[-1] : 5 print "five[-2] : ", five[-2] # five[-2] : 4 print "five[:] : ", five[:] # five[:] : (1, 2, 3, 4, 5) print "five[0:4] : ", five[0:4] # five[0:4] : (1, 2, 3, 4) print "five[1:2] : ", five[1:2] # five[1:2] : (2,) print "five[:2] : ", five[:2] # five[:2] : (1, 2) print "five[:-1] : ", five[:-1] # five[:-1] : (1, 2, 3, 4) print "five[:9] : ", five[:9] # five[:9] : (1, 2, 3, 4, 5) #------------------------------------------------------------------ mix = (1, 2, "solaris", (1, 2, 3)) print "mix[1] :", mix[1] # mix[1] : 2 print "mix[2] :", mix[2] # mix[2] : solaris print "mix[3] :", mix[3] # mix[3] : (1, 2, 3) print "mix[3][0] :", mix[3][0] # mix[3][0] : 1 print "mix[3][1] :", mix[3][1] # mix[3][1] : 2 print "mix[3][2] :", mix[3][2] # mix[3][2] : 3 #------------------------------------------------------------------ s = " Eagle " s2 = s.rstrip() s3 = s.lstrip() s4 = s.strip() print s, len(s) # Eagle 8 print s2, len(s2) # Eagle 6 print s3, len(s3) # Eagle 7 print s4, len(s4) # Eagle 5 #------------------------------------------------------------------ print "Incompatible, it don't matter though\n'cos someone's bound to hear my cry" print "Speak out if you do\nYou're not easy to find" #------------------------------------------------------------------ print "12" == "12" # True print "17" == "9" # False print "aa" == "ab" # False print "abc" != "bce" # True print "efg" != "efg" # False #------------------------------------------------------------------ import math pi = 3.14 print math.cos(3) # -0.9899924966 print math.pi # 3.14159265359 print math.sin(3) # 0.14112000806 print pi # 3.14
article
Sunday, May 29, 2016
Python String and Variables Example Code
Python String and Variables Example Code
Python Package Example
Python Package Example
#A package is a collection of modules which have a common purpose. Technically a package is a directory which must have one special file called __init__.py #user interface code structure #read.py #constants/ # __init__.py #names.py #In our current working directory we have a constants directory and a read.py script. # __init__.py from names import names # import names (names.py) print "initializing constants package" # names.py names = ('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom') # read.py = root directory import constants # import constants (folder name constants) print constants.names #output #initializing constants package #('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom') # create subpackages. To access subpackages, we use the dot operator #read.py #constants/ #__init__.py #names.py #numbers/ #__init__.py #integers.py #This is the new hierarchy. We have a subpackage called numbers. #constant/numbers/__init__.py from integers import integers # integers.py integers = (2, 3, 45, 6, 7, 8, 9) # read.py import constants import constants.numbers as int print constants.names print int.integers #output #initializing constants package #('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom') #(2, 3, 45, 6, 7, 8, 9)
Python OOP object oriented programming Example code
Python OOP object oriented programming Example code
#OOP object oriented programming #class keyword class First: pass fr = First() print type(fr) print type(First) #--------------------------------------------------------------------- class Cat: def __init__(self, name): self.name = name missy = Cat('Missy') lucky = Cat('Lucky') print missy.name # Missy print lucky.name # Lucky #--------------------------------------------------------------------- class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age missy = Cat('Missy', 3) lucky = Cat('Lucky', 5) print missy.name, missy.age # Missy 3 print lucky.name, lucky.age # Lucky 5 print Cat.species # mammal print missy.__class__.species # mammal print lucky.__class__.species # mammal #--------------------------------------------------------------------- #Methods #Methods are functions defined inside the body of a class class Circle: pi = 3.141592 def __init__(self, radius=1): self.radius = radius def area(self): return self.radius * self.radius * Circle.pi def setRadius(self, radius): self.radius = radius def getRadius(self): return self.radius c = Circle() c.setRadius(5) print c.getRadius() # 5 print c.area() # 78.5398 #--------------------------------------------------------------------- class Methods: def __init__(self): self.name = 'Methods' def getName(self): return self.name m = Methods() print m.getName() # Methods print Methods.getName(m) # Methods #--------------------------------------------------------------------- #Inheritance #inheritance is a way to form new classes using classes that have already been defined class Animal: def __init__(self): print "Animal created" def whoAmI(self): print "Animal" def eat(self): print "Eating" class Dog(Animal): def __init__(self): Animal.__init__(self) print "Dog created" def whoAmI(self): print "Dog" def bark(self): print "Woof!" d = Dog() d.whoAmI() d.eat() d.bark() #--------------------------------------------------------------------- class Animal: def __init__(self, name=''): self.name = name def talk(self): pass class Cat(Animal): def talk(self): print "Meow!" class Dog(Animal): def talk(self): print "Woof!" a = Animal() a.talk() c = Cat("Missy") c.talk() d = Dog("Rocky") d.talk() # Meow! Woof! #--------------------------------------------------------------------- #Special Methods name class Book: def __init__(self, title, author, pages): print "A book is created" self.title = title self.author = author self.pages = pages def __str__(self): return "Title:%s , author:%s, pages:%s " % \ (self.title, self.author, self.pages) def __len__(self): return self.pages def __del__(self): print "A book is destroyed" book = Book("Inside Steve's Brain", "Leander Kahney", 304) print book print len(book) del book
Python List Example code
Python List Example code
#!/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'];
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()
Subscribe to:
Posts (Atom)