#!/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()
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()
wxpython Check menu item Example
wxpython Check menu item Example
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): menubar = wx.MenuBar() fileMenu = wx.Menu() viewMenu = wx.Menu() #hide a statusbar and a toolbar self.shst = viewMenu.Append(wx.ID_ANY, 'Show statubar', 'Show Statusbar', kind=wx.ITEM_CHECK) self.shtl = viewMenu.Append(wx.ID_ANY, 'Show toolbar', 'Show Toolbar', kind=wx.ITEM_CHECK) viewMenu.Check(self.shst.GetId(), True) #check menu item true viewMenu.Check(self.shtl.GetId(), True) # both statusbar and toolbar are visible self.Bind(wx.EVT_MENU, self.ToggleStatusBar, self.shst) self.Bind(wx.EVT_MENU, self.ToggleToolBar, self.shtl) menubar.Append(fileMenu, '&File') menubar.Append(viewMenu, '&View') self.SetMenuBar(menubar) self.toolbar = self.CreateToolBar() self.toolbar.AddLabelTool(1, '', wx.Bitmap('img/buttonforward.jpg')) self.toolbar.AddLabelTool(1, '', wx.Bitmap('img/buttonnext.jpg')) self.toolbar.Realize() self.statusbar = self.CreateStatusBar() self.statusbar.SetStatusText('Ready') self.SetSize((350, 250)) self.SetTitle('Check menu item') self.Centre() self.Show(True) def ToggleStatusBar(self, e): if self.shst.IsChecked(): self.statusbar.Show() #if check is true the show status bar else: self.statusbar.Hide() def ToggleToolBar(self, e): if self.shtl.IsChecked(): self.toolbar.Show() #if check is true the show toolbar else: self.toolbar.Hide() def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
wxPython Submenus and separators Example
wxPython Submenus and separators Example
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): menubar = wx.MenuBar() fileMenu = wx.Menu() fileMenu.Append(wx.ID_NEW, '&New') fileMenu.Append(wx.ID_OPEN, '&Open') fileMenu.Append(wx.ID_SAVE, '&Save') fileMenu.AppendSeparator() #separator imp = wx.Menu() imp.Append(wx.ID_ANY, 'Import newsfeed list...') imp.Append(wx.ID_ANY, 'Import bookmarks...') imp.Append(wx.ID_ANY, 'Import mail...') fileMenu.AppendMenu(wx.ID_ANY, 'I&mport', imp) qmi = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit\tCtrl+W') fileMenu.AppendItem(qmi) self.Bind(wx.EVT_MENU, self.OnQuit, qmi) menubar.Append(fileMenu, '&File') self.SetMenuBar(menubar) self.SetSize((350, 250)) self.SetTitle('Submenus and separators') 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 Icons and shortcuts Example
wxPython Icons and shortcuts Example
import wx APP_EXIT = 1 class myframe(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, title="Hello") self.InitUI() def InitUI(self): menubar = wx.MenuBar() fileMenu = wx.Menu() qmi = wx.MenuItem(fileMenu, 100, '&Quit\tCtrl+Q') qmi.SetBitmap(wx.Image('quit.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap()) #quit.png root folder fileMenu.AppendItem(qmi) self.Bind(wx.EVT_MENU, self.OnQuit, id=100) menubar.Append(fileMenu, '&File') self.SetMenuBar(menubar) self.SetSize((250, 200)) self.SetTitle('Icons and shortcuts') self.Centre() self.Show(True) def OnQuit(self, e): self.Close() def main(): ex = wx.App() ex.locale = wx.Locale(wx.LANGUAGE_ENGLISH) myframe() ex.MainLoop() if __name__ == '__main__': main()
wxPython simple menu example
wxPython simple menu example
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): menubar = wx.MenuBar() #menubar functionality fileMenu = wx.Menu() #menubar object fitem = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application') #menu object menubar.Append(fileMenu, '&File') self.SetMenuBar(menubar) self.Bind(wx.EVT_MENU, self.OnQuit, fitem) #bind the wx.EVT_MENU self.SetSize((300, 200)) self.SetTitle('Simple menu') 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 frame example
wxPython frame example
import wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, size=(300, 200)) #self.Move((800, 250)) #self.Centre() #center window on our screen self.Show() if __name__ == '__main__': app = wx.App() Example(None, title='Size and position') app.MainLoop()
Thursday, May 19, 2016
wxPython Phone Book using data grid view and sqlite3 database
wxPython Phone Book using data grid view and sqlite3 database
Create database table
CREATE TABLE Phone (
Create database table
CREATE TABLE Phone (
ID INTEGER (11) PRIMARY KEY,
name VARCHAR (255),
surname VARCHAR (255),
telephone VARCHAR (255)
);
save the sqlite3 file as wx_gui_database.db in a folder called Data and place it in the same directory as your python scriptimport wx import wx.grid import os import sqlite3 import re import string import gettext cwd = os.path.abspath(os.curdir) def connect():#this is the sqlite3 connection con_str=cwd + '/Data/wx_gui_database.db' cnn = sqlite3.connect(con_str) return cnn cnn.close() def data_rows_count():# to count the rows in the database con = connect() cur=con.cursor() cur.execute("SELECT * FROM Phone") rows=cur.fetchall() i=0 for r in rows: i+=1 return i def fmtstr(fmt, strr):# to format some string!!! res = [] i = 0 s=re.sub(r'[^\w]','',strr) for c in fmt: if c == '#': res.append(s[i:i+1]) i = i+1 else: res.append(c) res.append(s[i:]) return string.join(res) def titling(name):# to display the names and surnames in uppercase for 1st letter return name.title() def single_quote_remover(text):# to remove single quotes from entry to prevent SQL crash return text.replace ("'","/") def single_quote_returner(text):# to display the single quote for the user ex: cote d'or as chocolat:))) return text.replace("/","'") class MyFrame(wx.Frame):# this is the parent frame def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.frame_1_menubar = wx.MenuBar() wxglade_tmp_menu = wx.Menu() wxglade_tmp_menu.Append(1, _("Index"), "", wx.ITEM_NORMAL) self.frame_1_menubar.Append(wxglade_tmp_menu,_("Phone Book")) wxglade_tmp_menu = wx.Menu() wxglade_tmp_menu.Append(2, _("Message"), "", wx.ITEM_NORMAL) self.frame_1_menubar.Append(wxglade_tmp_menu,_("About")) self.SetMenuBar(self.frame_1_menubar) self.__set_properties() self.__do_layout() self.Bind(wx.EVT_MENU, self.open_dialog, id=1) self.Bind(wx.EVT_MENU,self.open_dialog1,id =2) def __set_properties(self): self.SetTitle(_("MyPhoneBook")) self.SetSize((555, 444)) self.SetBackgroundColour(wx.Colour(255, 255, 255)) def __do_layout(self): sizer_1 = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer_1) self.Layout() def open_dialog(self, event): MyDialog1(self).Show() def open_dialog1(self,event): wx.MessageBox("A simple wxpython PhoneBook that resumes basic graphical sqlite3 database configuration\n\n ") class MyDialog1(wx.Dialog):# this is the PhoneBook dialog box... def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_DIALOG_STYLE wx.Dialog.__init__(self, *args, **kwds) self.label_10 = wx.StaticText(self, -1, _(" ID")) self.txtID = wx.TextCtrl(self, -1, "") self.label_11 = wx.StaticText(self, -1, _(" Name")) self.txtNAME = wx.TextCtrl(self, -1, "") self.label_12 = wx.StaticText(self, -1, _(" Surname")) self.txtSURNAME = wx.TextCtrl(self, -1, "") self.label_13 = wx.StaticText(self, -1, _(" Number")) self.txtNUMBER = wx.TextCtrl(self, -1, "") self.button_6 = wx.Button(self, -1, _("UPDATE")) self.button_5 = wx.Button(self, -1, _("ADD")) self.button_7 = wx.Button(self, -1, _("DELETE")) self.button_8 = wx.Button(self, -1, _("LOAD")) self.grid_1 = wx.grid.Grid(self, -1, size=(1, 1)) self.label_14 = wx.StaticText(self, -1, _(" Search Name:")) self.txtSearch = wx.TextCtrl(self, -1, "") self.button_9 = wx.Button(self, -1, _(" Go")) self.button_10 = wx.Button(self, -1, _("Renumber")) self.txtNAME.SetFocus() self.button_6.Enabled=False self.txtID.Enabled=False self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self.clk_add, self.button_5) self.Bind(wx.EVT_BUTTON, self.clk_update, self.button_6) self.Bind(wx.EVT_BUTTON, self.clk_delete, self.button_7) self.Bind(wx.EVT_BUTTON, self.clk_load, self.button_8) self.Bind(wx.EVT_BUTTON, self.clk_go, self.button_9) self.Bind(wx.EVT_BUTTON, self.clk_renumber, self.button_10) def refresh_data(self): cnn =connect() cur = cnn.cursor() cur.execute("SELECT * FROM Phone") rows=cur.fetchall() for i in range (0,len(rows)): for j in range(0,4): cell = rows[i] self.grid_1.SetCellValue(i,j,str(cell[j])) def __set_properties(self): self.SetTitle(_("PyPhone")) self.SetSize((600, 550)) self.txtID.SetMinSize((120, 27)) self.txtNAME.SetMinSize((120, 27)) self.txtSURNAME.SetMinSize((120, 27)) self.txtNUMBER.SetMinSize((120, 27)) r=data_rows_count() self.grid_1.CreateGrid(r, 4)#this is to create the grid with same rows as database self.grid_1.SetColLabelValue(0, _("ID")) self.grid_1.SetColSize(0, 12) self.grid_1.SetColLabelValue(1, _("NAME")) self.grid_1.SetColSize(1, 150) self.grid_1.SetColLabelValue(2, _("SURNAME")) self.grid_1.SetColSize(2, 150) self.grid_1.SetColLabelValue(3, _("NUMBER")) self.grid_1.SetColSize(3, 150) self.txtSearch.SetMinSize((100, 27)) self.refresh_data() def __do_layout(self): sizer_4 = wx.BoxSizer(wx.VERTICAL) grid_sizer_4 = wx.GridSizer(1, 4, 0, 0) grid_sizer_3 = wx.GridSizer(4, 3, 0, 0) sizer_4.Add((20, 20), 0, 0, 0) grid_sizer_3.Add(self.label_10, 0, 0, 0) grid_sizer_3.Add(self.txtID, 0, 0, 0) grid_sizer_3.Add(self.button_5, 0, 0, 0) grid_sizer_3.Add(self.label_11, 0, 0, 0) grid_sizer_3.Add(self.txtNAME, 0, 0, 0) grid_sizer_3.Add(self.button_6, 0, 0, 0) grid_sizer_3.Add(self.label_12, 0, 0, 0) grid_sizer_3.Add(self.txtSURNAME, 0, 0, 0) grid_sizer_3.Add(self.button_7, 0, 0, 0) grid_sizer_3.Add(self.label_13, 0, 0, 0) grid_sizer_3.Add(self.txtNUMBER, 0, 0, 0) grid_sizer_3.Add(self.button_8, 0, 0, 0) sizer_4.Add(grid_sizer_3, 1, wx.EXPAND, 0) sizer_4.Add(self.grid_1, 1, wx.EXPAND, 0) sizer_4.Add((20, 20), 0, 0, 0) grid_sizer_4.Add(self.label_14, 0, wx.ALIGN_CENTER_VERTICAL, 0) grid_sizer_4.Add(self.txtSearch, 0, wx.ALIGN_CENTER_VERTICAL, 0) grid_sizer_4.Add(self.button_9, 0, wx.ALIGN_CENTER_VERTICAL, 0) grid_sizer_4.Add(self.button_10, 0, wx.ALIGN_CENTER_VERTICAL, 0) sizer_4.Add(grid_sizer_4, 1, wx.EXPAND, 0) self.SetSizer(sizer_4) self.Layout() def clear_grid(self): self.txtID.Value="" self.txtNAME.Value="" self.txtSURNAME.Value="" self.txtNUMBER.Value="" def auto_number(self): j=data_rows_count() return j+1 def clk_add(self, event): if self.txtNAME.Value == "" or self.txtSURNAME.Value == "" or self.txtNUMBER.Value == "": wx.MessageBox("Some Fields Are Empty!") else: the_id=str(self.auto_number()) the_name=single_quote_remover(str(self.txtNAME.Value)) the_surname=single_quote_remover(str(self.txtSURNAME.Value)) num=fmtstr('##-######',(str(self.txtNUMBER.Value)))#set the format here to the country u want name=titling(the_name) surname=titling(the_surname) self.grid_1.AppendRows(1) cnn = connect() cursor = cnn.cursor() add_many = "INSERT INTO Phone(ID,name,surname,telephone) VALUES("+(the_id)+",'"+(name)+"','"+(surname)+"','"+(num)+"')" cursor.execute(add_many) cnn.commit() cnn.close() self.refresh_data() self.clear_grid() self.txtNAME.SetFocus() event.Skip() def clk_update(self, event): try: num=fmtstr('##-######',str(self.txtNUMBER.Value)) the_name=single_quote_remover(str(self.txtNAME.Value)) the_surname=single_quote_remover(str(self.txtSURNAME.Value)) name=titling(the_name) surname=titling(the_surname) row_index = self.grid_1. GetSelectedRows()[0] c=self.grid_1.GetCellValue(row_index,0) cnn=connect() cur=cnn.cursor() cur.execute("UPDATE Phone SET name = "+ "'"+(name)+"'" + " ,surname="+ "'"+(surname)+"'" +",telephone=" + "'" +(num) + "'" + "WHERE ID="+"'" + str(c) + "'") cnn.commit() cnn.close() self.refresh_data() cnn.close() self.clear_grid() self.button_6.Enabled=False self.button_5.Enabled=True self.txtNAME.SetFocus() event.Skip() except IndexError: wx.MessageBox("you have lost focus on the row you wanted to edit") def clk_delete(self, event): try: lst = self.grid_1. GetSelectedRows()[0] c=self.grid_1.GetCellValue(lst,0) cnn=connect() cur=cnn.cursor() cur.execute("DELETE FROM Phone WHERE ID="+"'" + str(c) + "'") cnn.commit() cnn.close() self.grid_1.DeleteRows(lst,1) self.refresh_data() self.txtNAME.SetFocus() except IndexError: wx.MessageBox("You Did Not Select Any Row To Delete!") event.Skip() def clk_load(self, event): try: row_index = self.grid_1.GetSelectedRows()[0] cell_value=[] for i in range(0,4): cell_value.append(self.grid_1.GetCellValue(row_index,i)) self.txtID.Value= str(cell_value[0]) self.txtNAME.Value=str(cell_value[1]) self.txtSURNAME.Value=str(cell_value[2]) self.txtNUMBER.Value=str(cell_value[3]) self.button_6.Enabled=True self.button_5.Enabled=False self.txtNAME.SetFocus() event.Skip() except IndexError: wx.MessageBox("You Did Not Select Any Row To Load") def clk_go(self, event): r=data_rows_count() for e in range(0,r): for f in range(0,4): self.grid_1.SetCellValue(e,f,"") cnn=connect() cursor=cnn.cursor() cursor.execute("SELECT * FROM Phone WHERE name LIKE '%"+self.txtSearch.Value+"%'") cnn.commit() rows=cursor.fetchall() for i in range(len(rows)): for j in range(0,4): cell=rows[i] self.grid_1.SetCellValue(i,j,str(cell[j])) cnn.close() self.txtSearch.SetFocus() event.Skip() def clk_renumber(self, event): Backup_Messasse=wx.MessageDialog(None, "It Is Preferable To Backup Your Database Before You Continue! Do You Wish To Proceed?",'Caution!',wx.YES_NO | wx.ICON_QUESTION) Response=Backup_Messasse.ShowModal() if(Response==wx.ID_NO): Backup_Messasse.Destroy() if(Response==wx.ID_YES): cnn = connect() cur = cnn.cursor() cur.execute("SELECT * FROM Phone") rows=cur.fetchall() i=0 m=() for r in rows: i+=1 s=str(r).replace(str(r[0]),str(i)) t=s.replace ("u'","'") x=eval(t) m+=(x,) cur.execute("DELETE FROM Phone") add_many="INSERT INTO Phone VALUES(?,?,?,?)" cur.executemany(add_many,m) wx.MessageBox("Renumbering Successful!") cur.execute("SELECT * FROM Phone") TheRows = cur.fetchall() for i in range(len(TheRows)): for j in range(0,4): cell=TheRows[i] self.grid_1.SetCellValue(i,j,str(cell[j])) cnn.commit() cnn.close() self.txtNAME.SetFocus() event.Skip() if __name__ == "__main__": gettext.install("app") app = wx.App(False) #wx.InitAllImageHandlers() frame_1 = MyFrame(None, wx.ID_ANY, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop()
Saturday, May 14, 2016
Custom Authentication Sign In Sign Up in Laravel
Custom Authentication Sign In Sign Up in Laravel
Create dabase Table
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`remember_token` varchar(255) NOT NULL,
`updated_at` varchar(255) NOT NULL,
`created_at` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Assign routes URL http://localhost/laravel/login
laravel\app\Http\routes.php
laravel\resources\views\login.blade.php
Create dabase Table
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`remember_token` varchar(255) NOT NULL,
`updated_at` varchar(255) NOT NULL,
`created_at` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Assign routes URL http://localhost/laravel/login
laravel\app\Http\routes.php
Route::get('login',function(){ return view('login'); }); Route::post ( '/login', 'MainController@login' ); Route::post ( '/register', 'MainController@register' ); Route::get ( '/logout', 'MainController@logout' );Create Login template
laravel\resources\views\login.blade.php
<!DOCTYPE html> <html lang="en"> <head> <title>Custom Authentication in Laravel</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{{ asset('/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet" type="text/css" /> <script src="{{ asset('/bootstrap/js/modernizr.min.js') }}"></script> <script src="{{ asset('/bootstrap/js/bootstrap.min.j') }}"></script> <script src="{{ asset('/bootstrap/js/jquery.min.js') }}"></script> </head> <body id="page-top" class="index"> <!-- Navigation --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#page-top">Start Bootstrap</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="hidden"> <a href="#page-top"></a> </li> <li class="page-scroll"> <a href="#home">Home</a> </li> @if (session()->get('name')) <li class="laravel-right">Welcome {{session()->get('name') }} , <a class="laravel-right" href="/laravel/logout">Logout</a> </li> @else <li class="laravel-right"><a class="laravel-green" href="#" id="auth" onclick="document.getElementById('authentication').style.display='block'">Login / SignUp</a></li> @endif </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <section class="content"> <div class="container"> <div class="row"> <div id="authentication" class="laravel-modal"> <span onclick="document.getElementById('authentication').style.display='none'" class="laravel-closebtn laravel-grey laravel-hover-red laravel-container laravel-padding-16 laravel-display-topright">X</span> <div class="laravel-modal-content laravel-card-8 laravel-animate-zoom" style="max-width: 600px"> <div class="col-md-6 laravel-card-8 laravel-teal" onclick="openForm('Login')"> <h3>Sign In</h3> </div> <div class="col-md-6 laravel-card-8 laravel-teal" onclick="openForm('Register')"> <h3>Sign Up</h3> </div> <div style="margin-top: 25px !important;"> <div id="Login" class="laravel-container form"> <div class="laravel-container "> <div class="laravel-section"> <br> <br>@if (count($errors->login) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->login->all() as $error) <P>{{ $error }}</p> @endforeach </ul> </div> @endif @if (Session::has('message')) <div class="alert alert-warning">{{ Session::get('message') }}</div> @endif <form action="/laravel/login" method="POST"> {{ csrf_field() }} <input type="hidden" class="form-control" name="redirurl" value="{{ $_SERVER['REQUEST_URI'] }}"> <div class="form-group"> <label><b>Username</b></label> <input name="username" class="form-control" type="text" placeholder="Enter Username" required> </div> <div class="form-group"> <label><b>Password</b></label> <input class="form-control" name="password" type="password" placeholder="Enter Password" required> </div> <div class="form-group"><input type="submit" class="btn btn-success" value="Login" style="width:100%;"></div> <div class="checkbox"><label><input type="checkbox" checked="checked"> Remember me</label> </form> </div> </div> <div class="laravel-container laravel-border-top laravel-padding-16 "> <button onclick="document.getElementById('authentication').style.display='none'" type="button" class="btn btn-danger">Cancel</button> <span class="laravel-right laravel-padding laravel-hide-small">Forgot <a href="#">password?</a></span> </div> </div> </div> <div id="Register" class="laravel-container form "> <div class="laravel-container"> <div class="laravel-section"> <br> <br> @if (count($errors->register) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->register->all() as $error) <P>{{ $error }}</p> @endforeach </ul> </div> @endif <form action="/laravel/register" method="POST" id="regForm"> {{ csrf_field() }} <input type="hidden" name="redirurl" value="{{ $_SERVER['REQUEST_URI'] }}"> <div class="form-group"> <label><b>Email</b></label> <input class="form-control" type="text" name="email" placeholder="Enter Email" value="{{ old('email') }}" required> </div> <div class="form-group"> <label><b>Username</b></label> <input class="form-control" type="text" name="name" placeholder="Enter username" required value="{{ old('name') }}"> </div> <div class="form-group"> <label><b>Password</b></label> <input class="form-control" type="password" name="password" required placeholder="Enter Password"> </div> <div class="form-group"> <label><b>Confirm Password</b></label> <input class="form-control" required type="password" name="password_confirmation" placeholder="Enter Password"> </div> <div class="form-group"><input type="submit" class="btn btn-success" value="SignUp" style="width:100%;"></div> </form> </div> </div> <div class="laravel-container laravel-border-top laravel-padding-16 "> <button onclick="document.getElementById('authentication').style.display='none'" type="button" class="btn btn-danger">Cancel</button> </div> </div> </div> </div> <div class="fluid-container"></div> </div> </div> </section> <script> openForm("Login"); function openForm(formName) { var x = document.getElementsByClassName("form"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } document.getElementById(formName).style.display = "block"; } </script> @if (Session::has('message')) <script> $('#auth').click(); </script> @endif @if($errors->login->any()) <script> $('#auth').click();</script> @endif @if($errors->register->any()) <script> $('#auth').click(); openForm('Register');</script> @endif <style> .navbar { font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif; text-transform: uppercase; font-weight: 700; } .navbar a:focus { outline: none; } .navbar .navbar-nav { letter-spacing: 1px; } .navbar .navbar-nav li a:focus { outline: none; } .navbar-default, .navbar-inverse { border: none; } .laravel-modal { z-index: 3; display: none; padding-top: 100px; position: fixed; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4); } .laravel-grey, .laravel-hover-grey:hover { color: #000!important; background-color: #9e9e9e!important; } .laravel-container { padding: 0.01em 16px; } .laravel-padding-16, .laravel-padding-hor-16 { padding-top: 16px!important; padding-bottom: 16px!important; } .laravel-display-topright { position: absolute; right: 0; top: 0; } .laravel-closebtn { text-decoration: none; float: right; font-size: 24px; font-weight: bold; color: inherit; } .laravel-animate-zoom { -webkit-animation: animatezoom 0.6s; animation: animatezoom 0.6s; } .laravel-card-8 { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19)!important; } .laravel-modal-content { margin: auto; background-color: #fff; position: relative; padding: 0; outline: 0; width: 600px; } .laravel-teal, .laravel-hover-teal:hover { color: #fff!important; background-color: #009688!important; } .laravel-card-8 { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19)!important; } .laravel-section { margin-top: 36px!important; margin-bottom: 16px!important; } .laravel-green, .laravel-hover-green:hover { color: #fff!important; background-color: #4CAF50!important; } .laravel-right { float: right!important; } </style> </body> </html>
Create Controller
laravel\app\Http\Controllers\MainController.php<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use Hash; use Auth; use Redirect; use Session; use Validator; use Illuminate\Support\Facades\Input; class MainController extends Controller { public function login(Request $request) { $rules = array ( 'username' => 'required', 'password' => 'required' ); $validator = Validator::make ( Input::all (), $rules ); if ($validator->fails ()) { return Redirect::back ()->withErrors ( $validator, 'login' )->withInput (); } else { if (Auth::attempt ( array ( 'name' => $request->get ( 'username' ), 'password' => $request->get ( 'password' ) ) )) { session ( [ 'name' => $request->get ( 'username' ) ] ); return Redirect::back (); } else { Session::flash ( 'message', "Invalid Credentials , Please try again." ); return Redirect::back (); } } } public function register(Request $request) { $rules = array ( 'email' => 'required|unique:users|email', 'name' => 'required|unique:users|alpha_num|min:4', 'password' => 'required|min:6|confirmed' ); $validator = Validator::make ( Input::all (), $rules ); if ($validator->fails ()) { return Redirect::back ()->withErrors ( $validator, 'register' )->withInput (); } else { $user = new User (); $user->name = $request->get ( 'name' ); $user->email = $request->get ( 'email' ); $user->password = Hash::make ( $request->get ( 'password' ) ); $user->remember_token = $request->get ( '_token' ); $user->save (); return Redirect::back (); } } public function logout() { Session::flush (); Auth::logout (); return Redirect::back (); } }
localhost url http://localhost/laravel/login
Subscribe to:
Posts (Atom)