Wednesday, 14 March 2018

Python tkinter advanced gui - Day 19


  • #weight property ,is used so that we can decide which rows and columns should remain less expandable or minimizable when maximizing the window or shrinking it. titles buttons should have less weight where as scroll bar,list should have more weight

  •   
    import tkinter
    import os
    
    mainwindow = tkinter.Tk()
    mainwindow.title("GRID DEMO")
    mainwindow.geometry('600x480-8-200')
    
    label =tkinter.Label(mainwindow,text ='tkinter grid demo label')
    label.grid(row=0,column=0,columnspan = 3)
    
    mainwindow.columnconfigure(0,weight=1)
    mainwindow.columnconfigure(1,weight=1)
    mainwindow.columnconfigure(2,weight=3)
    mainwindow.columnconfigure(3,weight=3)
    mainwindow.columnconfigure(4,weight=3)
    mainwindow.rowconfigure(0,weight=1)
    mainwindow.rowconfigure(1,weight=10)
    mainwindow.rowconfigure(2,weight=1)
    mainwindow.rowconfigure(3,weight=3)
    mainwindow.rowconfigure(4,weight=3)
    
    filelist =tkinter.Listbox(mainwindow)
    filelist.grid(row=1,column=0,sticky = 'nsew',rowspan=2)
    filelist.config(border=2,relief = 'sunken')
    for zone in os.listdir('/Windows/System32/drivers/'):#sample path
        filelist.insert(tkinter.END,zone)
    
    listscroll = tkinter.Scrollbar(mainwindow,orient = tkinter.VERTICAL,command = filelist.yview)
    listscroll.grid(row = 1,column=1,sticky = 'nsw',rowspan=2)
    filelist['yscrollcommand']=listscroll.set
    
    optionframe = tkinter.LabelFrame(mainwindow,text = 'File Details')
    optionframe.grid(row=1,column=2,sticky ='ne')
    
    rbvalue = tkinter.IntVar()
    rbvalue.set(3)#to set the default option for radiobutton
    
    #radio Buttons
    radio1= tkinter.Radiobutton(optionframe,text = 'FileName',value =1,variable =rbvalue)
    radio2= tkinter.Radiobutton(optionframe,text = 'Path',value =2,variable =rbvalue)
    radio3= tkinter.Radiobutton(optionframe,text = 'TimeStamp',value =3,variable =rbvalue)
    radio1.grid(row=0,column=0,sticky ='w')
    radio2.grid(row=1,column=0,sticky ='w')
    radio3.grid(row=2,column=0,sticky ='w')
    
    #widget to display the result
    resultLabel = tkinter.Label(mainwindow,text ="Result")
    resultLabel.grid(row=2,column=2,sticky='nw')
    result = tkinter.Entry(mainwindow)
    result.grid(row=2,column=2,sticky='sw')
    
    #Frame for Time Spinners
    timeFrame = tkinter.LabelFrame(mainwindow,text = 'Time')
    timeFrame.grid(row=3,column=0,sticky = 'new')
    #Time Spinners
    hourSpinner = tkinter.Spinbox(timeFrame,width=2,values = tuple(range(0,24)))
    minuteSpinner = tkinter.Spinbox(timeFrame,width=2,from_=0,to=59)
    secondSpinner = tkinter.Spinbox(timeFrame,width=2,values = tuple(range(0,60)))
    hourSpinner.grid(row=0,column=0)
    tkinter.Label(timeFrame,text=':').grid(row=0,column=1)
    minuteSpinner.grid(row=0,column=2)
    tkinter.Label(timeFrame,text=':').grid(row=0,column=3)
    secondSpinner.grid(row=0,column=4)
    timeFrame['padx']=36
    
    #Frame for Date Spinners
    dateFrame = tkinter.Frame(mainwindow)
    dateFrame.grid(row=4,column=0,sticky = 'new')
    #Date Labels
    dayLabel = tkinter.Label(dateFrame,text='Day')
    monthLabel = tkinter.Label(dateFrame,text='Month')
    yearLabel = tkinter.Label(dateFrame,text='Year')
    dayLabel.grid(row=0,column=0,sticky ='w')
    monthLabel.grid(row=0,column=1,sticky ='w')
    yearLabel.grid(row=0,column=2,sticky ='w')
    #Date Spinners
    daySpin = tkinter.Spinbox(dateFrame,width=5,from_=1,to=31)
    monthSpin = tkinter.Spinbox(dateFrame,width=5,values=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"))
    yearSpin = tkinter.Spinbox(dateFrame,width=5,from_=2000,to=2099)
    daySpin.grid(row=1,column=0)
    monthSpin.grid(row=1,column=1)
    yearSpin.grid(row=1,column=2)
    
    #buttons
    okButton = tkinter.Button(mainwindow,text = 'OK')
    cancelButton = tkinter.Button(mainwindow,text = 'Cancel',command = mainwindow.destroy)
    okButton.grid(row=4,column=3,sticky='e')
    cancelButton.grid(row=4,column=4,sticky='w')
    
    mainwindow.mainloop()
    print (rbvalue.get())#to confirm the selection of correct value in radio button
     
    

    Tuesday, 13 March 2018

    Python tkinter - Day 18(10 days later)



  • Tkinter provides classes which allow the display, positioning and control of widgets. Toplevel widgets are Tk and Toplevel. Other widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton, Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox LabelFrame and PanedWindow.

  •   
    import tkinter
    print(tkinter.TkVersion)
    print(tkinter.TclVersion)
    
    # tkinter._test()
    # or we can use the below piece of code
    
    mainWindowvar = tkinter.Tk()
    
    mainWindowvar.title('test')
    # mainWindow.geometry('2000x2000')
    #below code will specify the screen size and position of the
    #new window
    mainWindowvar.geometry('400x400-5-10')
    
    
    # # help(tkinter)
    #
    # labelvar = tkinter.Label(mainWindowvar,text = "this is label")
    # labelvar.pack(side = "top")
    #
    # canvasvar = tkinter.Canvas(mainWindowvar, relief = 'raised',borderwidth=1)
    # canvasvar.pack(side='left', anchor = 'n')
    # button1 = tkinter.Button(mainWindowvar,text = "button1")
    # button2 = tkinter.Button(mainWindowvar,text = "button2")
    # button3 = tkinter.Button(mainWindowvar,text = "button3")
    # button1.pack(side ='top')
    # button2.pack(side ='top')
    # button3.pack(side ='top')
    #
    # mainWindowvar.mainloop()
    
    
    # help(tkinter)
    
    #the above code will work but to make it proper we
    #can introduce frame
    
    labelvar = tkinter.Label(mainWindowvar,text = "this is label")
    labelvar.pack(side = "top")
    
    leftframevar = tkinter.Frame(mainWindowvar)
    leftframevar.pack(side='left',anchor = 'n',fill=tkinter.Y,expand =False)
    
    canvasvar = tkinter.Canvas(leftframevar, relief = 'raised',borderwidth=1)
    canvasvar.pack(side='left', anchor = 'n')
    
    rightframevar = tkinter.Frame(mainWindowvar)
    rightframevar.pack(side='right',anchor = 'n',fill=tkinter.Y,expand =True)
    
    button1 = tkinter.Button(rightframevar,text = "button1")
    button2 = tkinter.Button(rightframevar,text = "button2")
    button3 = tkinter.Button(rightframevar,text = "button3")
    button1.pack(side ='top')
    button2.pack(side ='top')
    button3.pack(side ='top')
    
    mainWindowvar.mainloop()
    
    
     
    

    Wednesday, 28 February 2018

    Python timezone challenge- Day 17


  • the challenge here is to let the user choose the time zone from list of time zones and accordingly display the time
  •   
    import datetime
    import pytz
    
    available_zones ={"1":"African/Tunis",
     "2":"Asia/Kolkata",
     "3":"Australia/Adelaide",
     "4":"Europe/Brussels",
     "5":"Europe/London",
     "6":"Japan",
     "7":"Pacific/Tahiti"
    }
    print("Please Choose the timezone (or 0 to quit)")
    for place in sorted(available_zones):
        print("\t {} : {}".format(place,available_zones[place]))
    
    while True:
        choice = input()
        if choice == 0:
            break
        if choice in available_zones.keys():
            tz_to_display = pytz.timezone(available_zones[choice])
            world_time = datetime.datetime.now(tz=tz_to_display)
            print ("The time in {} is {} {} ".format(available_zones[choice],
                                 world_time.strftime("%A %x %X %z"),world_time.tzname()))
            print("LocalTime is {}".format(datetime.datetime.now().strftime("%A %x %X %z")))
            print("UTCTime is {}".format(datetime.datetime.utcnow().strftime("%A %x %X %z")))
    
     
    

    Python timezone - Day 16(1 day later)


  • pip command,if it doesn't work ,open the python setup goto modify and check the add python to environment variables option python time zone library package,pip3 install pytz
  •   
    import pytz
    import datetime
    country = "Europe/Moscow" #check for the spelling and case sensitivity
    tz_to_display = pytz.timezone(country)
    # print(tz_to_display)
    # print(country)
    print("The time in {} is {}".format(country,datetime.datetime.now(tz=tz_to_display)))
    print("UTC is {}".format(datetime.datetime.utcnow()))
    print("LocalTime here is {}".format(datetime.datetime.now()))
    tz_to_display = pytz.timezone("Singapore")
    print("The time in {} is {}".format("Singapore",datetime.datetime.now(tz=tz_to_display)))
    
    #list of all timezones
    for x in pytz.all_timezones:
        print(x)
    print("=="*50)
    print(pytz.country_names)
    #list of all countries
    for x in pytz.country_names:
        print(x)
    
    for x in sorted(pytz.country_names):
        print(x + ": " + pytz.country_names[x])
    
    #although the below code will run,there will be error ,since the few countries
    #like (Bouvet Island ) have not defined the timezones
    # for x in sorted(pytz.country_names):
    #     print("{} : {} : {}".format(x,pytz.country_names[x],pytz.country_timezones(x)))
    
    print("=================="*10)
    #we can use the get method to avoid the below issue
    for x in sorted(pytz.country_names):
        print("{} : {} : {}".format(x,pytz.country_names[x],pytz.country_timezones.get(x)))
    print("*************"*10)
    #we can also use the below method
    for x in sorted(pytz.country_names):
        print("{} : {} ".format(x,pytz.country_names[x],end = ' '))
        if x in (pytz.country_timezones):
            print(pytz.country_timezones[x])
        else:
            print("TimeZone Not Defined")
     
    

    Monday, 26 February 2018

    Python date time calendar module - Day 15


  • time module
  •   
    # import time
    # # print(time.gmtime())
    # # ##epoch time
    # # print(time.gmtime(0))
    # # print("="*40)
    # # print(time.localtime())
    # # print("="*40)
    # # ##seconds till now from epoch time
    # # print(time.time())
    #
    # time_here = time.localtime()
    # print(time_here)
    # #time_here is a tuple ,we can make use of the tuple index or name ,so that
    # #we can get the desired part of the date
    # print("year:",time_here[0],time_here.tm_year)
    # print("Month:",time_here[1],time_here.tm_mon)
    # print("Day:",time_here[2],time_here.tm_mday)
    
    #reaction time game
    
    
    # import time
    # from time import time as my_timer
    # import random
    #
    # input("press enter to start")
    # wait_time = random.randint(1,6)
    # time.sleep(wait_time)
    # start_time=my_timer()
    # input("press enter to stop")
    # end_time=my_timer()
    #
    # print(start_time,end_time)
    # print("started at "+ time.strftime("%X",time.localtime(start_time)))
    # print("Ended at "+ time.strftime("%X",time.localtime(end_time)))
    # print("Time taken for response was {}".format(end_time-start_time))
    
    
  • #apart from the time method we also have three other methods that we can make use of #monotonic - this can be used ,so that even if there is daylight saving time,activates #in the mean time or the user changes the clock in system,always the end time #will be higher than the #start time if we use the monotonic #other 1 is perf_counter #and the process_time is the elapsed cpu time for the process #proposal for python - PEP 0418 can read from there
  • import time # # from time import perf_counter as my_timer # # from time import monotonic as my_timer # from time import process_time as my_timer # import random # # # input("press enter to start") # wait_time = random.randint(1,6) # time.sleep(wait_time) # start_time=my_timer() # input("press enter to stop") # end_time=my_timer() # # print(start_time,end_time) # print("started at "+ time.strftime("%X",time.localtime(start_time))) # print("Ended at "+ time.strftime("%X",time.localtime(end_time))) # print("Time taken for response was {}".format(end_time-start_time)) #info about the each clock print("time():\t\t\t",time.get_clock_info("time")) print("monotonic():\t",time.get_clock_info("monotonic")) print("perf_counter():\t",time.get_clock_info("perf_counter")) print("process_time():\t",time.get_clock_info("process_time"))

    Sunday, 25 February 2018

    Python Modules - Day 14(day later)


  • we can import modules using the module name and import keyword we can import the full module or specific functions in that module if there is any reference warning right click on the function and choose ignore unresolved references
  •   
    # import turtle
    #
    #
    # turtle.forward(400)
    # turtle.circle(250)
    # turtle.right(300)
    #
    # #the done function is used to hold the screen to see the result
    # #or else we can use the time module and sleep function
    #
    #
    # for i in range(0,100,10):
    #     turtle.forward(i)
    #     turtle.circle(i)
    #     turtle.right(i)
    #
    #
    # turtle.done()
    
    
    #if we need only the particular functions we can code like below
    # from turtle import circle,done
    #
    # circle(70)
    # done()
    
    #or else we can do use *
    # from turtle import *
    #
    # circle(70)
    # done()
    
    #we will get the error if we run the below piece of code
    #since the done is common here,we declared as string,but the turtle method
    #also has the "done" as function
    done = "done with the drawing"
    
    import turtle
    
    turtle.forward(400)
    turtle.circle(250)
    turtle.right(300)
    
    done()
    print(done)
    
    #here we can check the list of objects inside the
    #inbuilt modules of the python
    #we can also ctrl + click the module name to find the list of objects
    
    print(dir())
    #the above line will print
    
    #['__annotations__', '__builtins__', '__cached__', '__doc__',
    ## '__file__', '__loader__', '__name__', '__package__', '__spec__']
    print("="*40)
    for i in dir():
        print(i)
    print(dir('__builtins__'))
    #the above line will print
    
    #['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
    # '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
    # '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
    # '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
    # '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
    # 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
    # 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier',
    #  'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
    # 'lower',
    #  'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
    #  'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
    # 'translate', 'upper', 'zfill']
    
    print("="*40)
    for i in dir('__builtins__'):
        print(i)
    
    #lets check for the shelve now
    
    import shelve
    
    print(dir())
    # ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', 
    #'__name__',
    #  '__package__', '__spec__', 'i', 'shelve']
    
    print(dir(shelve))
    # ['BsdDbShelf', 'BytesIO', 'DbfilenameShelf', 'Pickler',
    # 'Shelf', 'Unpickler', '_ClosedDict', '__all__', '__builtins__',
    # '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
    # 'collections', 'open']
    print(dir(shelve.Shelf))
    print('=='*20)
    for i in dir(shelve.Shelf):
        print(i)
    
    
    
    #we can use the help function to know the functionality
    
    
    
    help(shelve)
    print("*"*20)
    help(shelve.Shelf)
    
    import  random
    help(random)
    print("*"*20)
    help(random.randint)
    
     
    

    Friday, 23 February 2018

    Python Shelve eg2....- Day 13


  • updating shelve
  •   
    import shelve
    # with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveeg3") as fruit:
    fruit = shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveeg3")
    fruit['orange']='citrus fruit'
    fruit['apple']='good for health'
    fruit['lemon']='small fruit'
    fruit['papaya']='good for eye'
    
    print(fruit)
    print(fruit['lemon'])
    
    fruit['lemon']='Can Make Juice'
    
    print(fruit)
    print(fruit['lemon'])
    
    for i in fruit:
        print(i +" - " + fruit[i])
    print("="*40)
    
    # while True:
    #     var1 = input("enter any fruit key - ")
    #     if var1 =='quit':
    #         break
    #     # print(fruit.get(var1,'entered key doent exits'))
    #     if var1 in fruit:
    #         print(fruit[var1])
    #     else:
    #         print('entered key does not exits')
    
    #to get the shelve in sorted order
    shelvesortlist = list(fruit.keys())
    shelvesortlist.sort()
    print(shelvesortlist)
    print(fruit)
    for var2 in shelvesortlist:
        print(var2+" - "+fruit[var2])
    print (fruit.values())
    print (fruit.items())
    print (fruit.keys())
    fruit.close()
    
    
    #the below example is not prefect,but the thing is there is a concept of writeback and sync
    #related to shelve object,which can be used to update the shelve based on memory usage
    #the benefits of these will be know later i guess.
    
    
    import shelve
    
    blt = ["bread","bacon","lettuce"]
    egg = ["boiled egg","Milk"]
    butter = ["cheese","butter"]
    pasta = ["pasta","macroni"]
    
    with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveupdateeg4") as recipes:
        recipes["blt"]=blt
        recipes["egg"]=egg
        recipes["butter"]=butter
        recipes["pasta"]=pasta
        print(recipes)
    
        for var1 in recipes:
            print(var1,recipes[var1])
    
    #in the eg above if we want to update the items against any key in shelve,
    #if we use append method ,it wont update the shelve like check using the below code
        recipes["egg"].append("omlette")
        for var1 in recipes:
            print(var1,recipes[var1])
    #we can update it correcty by changing the list itself and reassigning to the shelve
        templist = ["boiled egg","Milk","omlette"]
        recipes["egg"]=templist
        for var1 in recipes:
            print(var1,recipes[var1])
    
    print("="*40)
    with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveupdateeg4") as recipes:
        for var1 in recipes:
            print(var1,recipes[var1])
    print('*'*40)