Saturday, December 31, 2022

TwentyTwentyThree

It is a well known fact: Turtle is something of a Party Animal who would

enjoy ringing in the New Year at various Hot Spots around the world. So where 

should Turtle be at any given time during the day!

                                                                


 https://www.timeanddate.com/time/map/

Starting things off at 7 AM this morning in Montreal, 2023 is entering the scene in 

the Time Zone on the far right. How to calculate this: Adding 5 hours to mytime gives

UTC time, 12 noon in London. Adding 12 hours to that, it is midnight on the

other side of the world.


So keeping track during the, let us say at 8 AM mytime, it is then 1 in the afternoon

in London; (12 -1) hours away to the right, it is the New Year.


Have a good one, Turtle.

                                                      *     *     *

For a bit of background on the calendar module. The current one dates from

2017. It is straightforward.

                                                       


It is when we pair it with tkinter that things get intereting. That's

because it is the purpose of tkinter to provide GUIs ie user interfaces:

Our monthly numbers now show up in a text area.


Below, a full example with both an input and display area:

                                                 

from tkinter import *
import calendar

root = Tk()
# root.geometry("400x300")

root.title("Calendar")

# Function
def text():
month_int = int(month.get())
year_int = int(year.get())
cal = calendar.month(year_int, month_int)
textfield.delete(0.0, END)
textfield.insert(INSERT, cal)

# Creating Labels
label1 = Label(root, text="Month:")
label1.grid(row=0, column=0)

label2 = Label(root, text="Year:")
label2.grid(row=0, column=1)

# Creating spinbox
month = Spinbox(root, from_=1, to=12, width=8)
month.grid(row=1, column=0, padx=5)

year = Spinbox(root, from_=2000, to=2100, width=10)
year.grid(row=1, column=1, padx=10)

# Creating Button
button = Button(root, text="Go", command=text)
button.grid(row=1, column=2, padx=10)

# Creating Textfield
textfield = Text(root, width=25, height=10, fg="red")
textfield.grid(row=2, columnspan=2)

root.mainloop()

                                                                          


https://github.com/geekcomputers/Python/blob/master/Calendar%20(GUI)

Friday, December 30, 2022

TkCal

 I have been asked to produce a windows .exe file from the - now running -

tkcalendar project. Unfortunately, I cannot do this at the moment. Pyinstaller is

not (yet) compatible with python 3.10. Those still running an earlier version

of python should be able to quite easily.


Below, my running tkcal code. Note that there are many styling options I am not

using, and that many color schemes are possible. That's half the achievement of the

tkcal module, producing all that styling code for the calendar options. 


from tkinter import *
import tkinter.messagebox as mb
from tkinter import ttk
from tkcalendar import Calendar
import sqlite3
import datetime

#Create database
connector = sqlite3.connect('Calevents.db')
cursor = connector.cursor()
connector.execute(
"CREATE TABLE IF NOT EXISTS CALEVENTS (EVENT_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
"DAY TEXT, DESC TEXT, TAG TEXT )"
)

#show form with empty fields
def reset_fields():
global day_strvar, desc_strvar, tag_strvar
for i in ['day_strvar', 'desc_strvar', 'tag_strvar']:
exec(f"{i}.set('')")

#erase all current database entries
def reset_form():
import sqlite3

conn = sqlite3.connect('Calevents.db')
c = conn.cursor()

# delete all rows from table
c.execute('DELETE FROM CALEVENTS;', );

print('We have deleted', c.rowcount, 'records from the table.')

# commit the changes to db
conn.commit()
# close the connection
conn.close()

#display records and activate cal
def display_records():
tree.delete(*tree.get_children())
curr = connector.execute('SELECT * FROM CALEVENTS')
data = curr.fetchall()
for records in data:
tree.insert('', END, values=records)

date = datetime.datetime.strptime(records[1], "%Y-%m-%d").date()
my_cal.calevent_create(date, records[2], records[3])
my_cal.tag_config('out', background='turquoise')
my_cal.tag_config('home', background='plum')

# do_stuff_with_row
def add_record():
global day_strvar, desc_strvar, tag_strvar
day = day_strvar.get()
desc = desc_strvar.get()
tag = tag_strvar.get()

if not day or not desc or not tag:
mb.showerror('Error!', "Please fill all the missing fields!!")
else:
try:
connector.execute(
'INSERT INTO CALEVENTS (DAY, DESC, TAG) VALUES (?,?,?)',
(day, desc, tag)
)
connector.commit()
mb.showinfo('Record added', f"Record of {day} was successfully added")
reset_fields()
display_records()
except:
mb.showerror('Wrong type',
'The type of the values entered is not accurate.')

def remove_record():
if not tree.selection():
mb.showerror('Error!', 'Please select an item from the database')
else:
current_item = tree.focus()
values = tree.item(current_item)
selection = values["values"]
tree.delete(current_item)
connector.execute('DELETE FROM CALEVENTS' %selection[0])
connector.commit()
mb.showinfo('Done', 'The record you wanted deleted was successfully deleted.')
display_records()

def view_record():
global day_strvar, desc_strvar, tag_strvar

if not tree.selection():
mb.showerror('Error!', 'Please select a record to view')
else:

current_item = tree.focus()
values = tree.item(current_item)
selection = values["values"]

day_strvar.set(selection[1]); desc_strvar.set(selection[2])
tag_strvar.set(selection[3]);


date = datetime.datetime.strptime(selection[1], "%Y-%m-%d").date()
my_cal.tag_config('out', background='turquoise')
my_cal.tag_config('home', background='plum')
my_cal.calevent_create(date, selection[2], selection[3])

#initiating root
root=Tk()
root.title('My_Calevents')
root.geometry('800x400+400+200')
root.resizable(False, False)
root.update_idletasks()
lf_bg = 'seashell2' # bg color for the left_frame
cf_bg = 'grey77' # bg color for the center_frame

# Creating the StringVar or IntVar variables, and the calevents label
day_strvar = StringVar()
desc_strvar = StringVar()
tag_strvar = StringVar()
Label(root, text="CALEVENTS", bg='ivory').pack(side=TOP, fill=X)

#creating the frames
left_frame = Frame(root, bg=lf_bg)
left_frame.place(x=0, y=30, relheight=1, relwidth=0.2)

center_frame = Frame(root, bg=cf_bg)
center_frame.place(relx=0.2, y=30, relheight=1, relwidth=0.2)
right_frame = Frame(root, bg="Gray65")
right_frame.place(relx=0.4, y=30, relheight=1, relwidth=0.6)

# Placing components in the left frame
Label(left_frame, text="Day").place(relx=0.333, rely=0.05)
Label(left_frame, text="Description").place(relx=0.233, rely=0.18)
Label(left_frame, text="Tag").place(relx=0.333, rely=0.31)
Entry(left_frame, width=15, textvariable=day_strvar).place(x=20, rely=0.1)
Entry(left_frame, width=15, textvariable=desc_strvar).place(x=20, rely=0.23)
Entry(left_frame, width=15, textvariable=tag_strvar).place(x=20, rely=0.36)
Button(left_frame, text='Add Record', command=add_record, width=18).place(relx=0.025, rely=0.85)

# Placing components in the center frame
Button(center_frame, text='Delete Record', command=remove_record, width=14).place(relx=0.1, rely=0.25)
Button(center_frame, text='View Record', command=view_record, width=14).place(relx=0.1, rely=0.35)
Button(center_frame, text='Reset Fields', command=reset_fields, width=14).place(relx=0.1, rely=0.45)
Button(center_frame, text='Delete database', command=reset_form, width=14).place(relx=0.1, rely=0.55)

#Showing header in the right frame
Label(right_frame, text='Events Listing', bg='light steel blue', fg='purple').pack(side=TOP, fill=X)

#cal features
global my_cal
top=Toplevel(root)
top.resizable(False, False)
top.update_idletasks()
my_cal = Calendar(top, selectmode='day', showweeknumbers=False, locale='en_US',
date_pattern='y-mm-dd', selectbackground ='khaki3',
background='light yellow', foreground='purple', font='Ink_Free 12',
tooltipbackground='teal', tooltipalpha=.5, tooltipdelay=0)
my_cal.pack(side='right')

#the two buttons for showing or not the database features
def withdraw():
root.withdraw()
def show_win():
root.deiconify()
buttonW = Button(top, text='Close_Win', command=withdraw)
buttonW.pack()
buttonWD = Button(top, text="Show_Win", command=show_win)
buttonWD.pack()

#atyling the database entries
style = ttk.Style()
style.theme_use('vista')

#style.configure("Heading", font="Arial, 14, bold")
tree = ttk.Treeview(right_frame, height=100, selectmode=BROWSE,
columns=('ID', "Day", "Description", "Tag"))

X_scroller = Scrollbar(tree, orient=HORIZONTAL, command=tree.xview)
Y_scroller = Scrollbar(tree, orient=VERTICAL, command=tree.yview)
X_scroller.pack(side=BOTTOM, fill=X)
Y_scroller.pack(side=RIGHT, fill=Y)
tree.config(yscrollcommand=Y_scroller.set, xscrollcommand=X_scroller.set)
tree.heading('ID', text='ID', anchor=W)
tree.heading('Day', text='Day', anchor=W)
tree.heading('Description', text='Description', anchor=W)
tree.heading('Tag', text='Tag', anchor=W)
tree.column('#0', width=0, stretch=NO)
tree.column('#1', width=80, stretch=NO)
tree.column('#2', width=150, stretch=NO)
tree.column('#3', width=180, stretch=NO)
tree.place(y=30, relwidth=1, relheight=0.9, relx=0)

#calling display and update
display_records()
root.update()

#keeping the root window open
root.mainloop()

Finished

 So here is the secret - and it is what is fun about turtle - a goto is a forward

command. If the pen is up, nothing shows; but if pen is down, there is a line.

Below, I have removed the i in range(10) loop, so turtle is only doing a double.

The first triangle is completed because turtle subsequently returns to the center. 

The second is not because its work is finished...

                                                                       

                                                                              



                                                  


Another nice touch: the little knots in the circle. The original code calls for 4. 

Below, I have reduced it to 3. Not so cute...

                                                                      


*     *     *

With numbers for a smaller screen:

                                                                        



                                                                              

                                                                         

                                                                          

Then, moving the side decos up by thirty, and the right over by 10...

                                                                              

Thursday, December 29, 2022

Hard_P

 As of January1, fast food outlets in France will need to serve

those dining in with re-usable dishware. Below, there are concerns that

hard plastic may not wear well; remains to be seen...

                                                   


source: The Guardian

                                                       *     *     *

From copyassignment, some likeable turtle code to make a New Year's

Greeting. An enigma remains: turtle is only told to advance twice on each

petal, yet there are three sides. What gives...

                                                             


Will be working with this starter code tomorrow!

https://copyassignment.com/wishing-happy-new-year-2023-in-python-turtle/

Wednesday, December 28, 2022

Sober

 Been struggling to adapt the database interface to more general means. 

Treeview is a ttk widget, which should mean that styling is easier. Ha!

Turns out to be terribly resistant to anything fancy. I am, for the moment, 

on the default 'theme'. Maybe it was intended to keep things sober-looking.

                                                            




https://youtu.be/ewxT3ZEGKAA


Toned-down, with Vista theme, which sets the chosen record to blue.

                                                               


                                           

                                                       *     *     *




Tuesday, December 27, 2022

CallBack

 Turns out that the root window can be recalled with the deiconify function:

                                                             


                                                                               


Monday, December 26, 2022

Sometimes

Dr Oetker pudding is a Christmas staple with us. Actually prepared it by

beating it the full 5 minutes this year, and it turned out great.                                   



Also learned out to shave chocolate from a bar: very easy, just scrape...

                                                                         *     *     *


Sometimes, letting a problem rest - ignored - for a while can help.                    

Activating tkcal with the database data is actually a breeze!!

                                                             


                                                                     


Sunday, December 25, 2022

Saturday, December 24, 2022

Dedication

 A very large truck with a hose-like attachment worked on our parking

lot sewers in the middle of yesterday's storm. That was real dedication

on the part of those workers, and I am grateful.


Friday, December 23, 2022

Loner_Fun

 Poor little ones: deprived of a day of school because there

is a forecst of snow. Point of fact; it's a bit of rain and no wind...


Did find something the kids might have fun with: Soundtrap.

Put together and save little musical tidbits. Still getting

acquainted with the interface myself, but it does look like

fun.

                                                     




                                                

Thursday, December 22, 2022

Putin_esque

 I remember being quite fascinated with the figure of Rasputin in Russian history 

as an adolescent: a holistic healer avant l'heure. But then also a great seducer of

women, with many descendants...


A rather raunchy song about him was popular in Europe some years ago.



Any relation with the current leader: I have no idea. 'Putin' means road or way,

so it might be a quite prevalent name

Wednesday, December 21, 2022

Saturnalia

Winter solciste is today, at 4:48pm EST. Darkness will star to lift, 

but the cold is still ahead. Brrr...


By the mid 4th century, Romans were celebrating the winter solciste on

December 25, with rejoicing and gift exchanges...This was called Saturnlia,

after Saturn, the god of Time.


                                             

Below, a very interesting vid about London as a Roman city:

        

                                                      *     *     *

This is how the US Weather Service is calling the upcoming storm for the Richelieu Valley...

                                                                       



Tuesday, December 20, 2022

NewProb

 Today's problem : getting the database to show on true...

                                                            


*     *     *

After much trial and error, the cleanest approach is to have the database

as the root window, and the cal as a Toplevel window. I press the close window

button and I am left with an jupdated calendar...

                                                       



To actually delete the database:

                                                                        





Monday, December 19, 2022

Special

 I have been asked about how IntVar() works. Like StringVar(), only

for ints. The thing to notive here is that it involves a function call. The trace

method will trigger the updatewithoutthe user having to push any

buttons. All that needs to happen is that the value of the IntVar changes.

This special var has a set() method, which an ordinary variable doesn't have.

And thus a get() method as well. 


https://python-course.eu/tkinter/variable-classes-in-tkinter.php



https://www.plus2net.com/python/tkinter-IntVar.php

                                                                   *     *     *

Am currently, repopulating tkcal from an sqlite3 database. Albeit, one record

at a time. This CAN be done...


                                                


Sunday, December 18, 2022

Music

 Found code for a music player, below. It is very simple to make

using the pygame mixer. Just needs a little make-over:

https://copyassignment.com/simple-music-player-using-python/



Just add the song to the project folder:


*     *     *



                                                                              

                                                                             


                                                                               



Saturday, December 17, 2022

Gaining

 Below, a German language documentary that I found interesting in this: the clean

explanation on how too much insulin causes weight gain. One eats easily digested

sugary foods, the pancreas gets to work with insulin, to clear the blood. Instant weight

gain!!


Bon courage, Amberlynn!

Friday, December 16, 2022

Assignment

 We seem to be in for a three-day snow storm. What better time to build

a database.

Yes, I cannot avoid it. For all the fun I have been having with tkcalendar, it

does need a database backend to function properly. Found inspiration from

a project that already does this:


                                         


https://copyassignment.com/student-management-system-project-in-python/

                                                          *     *     *

I'm shameless: reproduced a simplified version of the above to accomodagte

TKcal. Performs as expected!

Adding  a record:

                                                                

 Asking to delete a record:

                                        


Viewing a record brings back the entries:






Reset Fields empties everything:



Delete database gets rid of all records: