Python Libraries
Transfer Bridge 2020
csv
Reading CSV files (Array)
import csv
with open('data.csv') as csvfile: #open csv file
# create reader object to read in the file
readCSV = csv.reader(csvfile)
# print a line out for each row
for row in readCSV:
print(row)
Name | Age | StudentID |
Blobby | 21 | 012345678 |
Jimin | 22 | 010101010 |
Pranav | 20 | 101010101 |
Sofia | 21 | 876543210 |
data.csv
Output:
['Name', 'Age', 'StudentID']
['Blobby', '21', '012345678']
['Jimin', '22', '010101010']
['Pranav', '20', '101010101']
['Sofia', '21', '876543210']
Reading CSV files (Dict)
import csv
with open('data.csv') as csvfile: #open csv file
# create Dictreader object to read in file
readCSV = csv.DictReader(csvfile)
# print a line out for each row
for row in readCSV:
print(row)
Output:
{'Name': 'Blobby', 'Age': '21', 'StudentID': '012345678'}
{'Name': 'Jimin', 'Age': '22', 'StudentID': '010101010'}
{'Name': 'Pranav', 'Age': '20', 'StudentID': '101010101'}
{'Name': 'Sofia', 'Age': '21', 'StudentID': '876543210'}
Name | Age | StudentID |
Blobby | 21 | 012345678 |
Jimin | 22 | 010101010 |
Pranav | 20 | 101010101 |
Sofia | 21 | 876543210 |
data.csv
tkinter
What is tkinter?
GUI
Initialize a Window
import tkinter as tk
def main():
# Create Tkinter window
window = tk.Tk()
window.title(‘Demo’)
“”” add widgets here “””
window.mainloop() # keep looping infinitely until there's a new event or the window is closed
main()
Widget Organization
Button
Widget Functions
Button Example
import tkinter as tk
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 600
def main():
window = tk.Tk()
button = tk.Button(window, text='Press', height=WINDOW_HEIGHT, width=35, command=window.destroy)
button.pack(side=‘top’) #pack to the top of the screen
window.mainloop()
main()
Canvas
Canvas Example
import tkinter as tk
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 600
def main():
# Create Tkinter window
window = tk.Tk()
my_canvas = tk.Canvas(window, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, bg='yellow')
my_canvas.pack() # make width and height adjustment works on the canvas
window.mainloop() # keep looping until there's a new event
main()
Draw Lines and Shapes on Canvas
Canvas Coordinate System
(x0, y0)
(x1, y1)
(x0, y0)
(x1, y1)
Drawing Example
import tkinter as tk
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 600
def main():
window = tk.Tk()
my_canvas = tk.Canvas(window, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, bg='yellow')
my_canvas.pack()
my_canvas.create_line(40, 50, 300, 100, 10, 150, fill='blue') #can use more than 2 points...
my_canvas.create_oval(30, 30, 50, 50, fill='purple')
my_canvas.create_rectangle(300, 75, 350, 125, fill='red')
window.mainloop() # keep looping until there's a new event
main()
References
https://www.geeksforgeeks.org/reading-csv-files-in-python/
https://docs.python.org/3/library/csv.html
https://www.geeksforgeeks.org/python-gui-tkinter/ **short ver. tkinter tutorial**
https://www.geeksforgeeks.org/introduction-to-tkinter/?ref=lbp **full tutorial**
https://docs.python.org/3/library/tkinter.html