My “naive” Python tutorial
Let's learn Python together with my "naive" method & make useful utility applications from scratch ...
... and you don't need any prior knowledge about Python ?? just open mind.
***
How to approach learning as an activity?
That is very often a dilemma for educators in any field of human knowledge. Experts who are well educated and skilled in some topics are not always great motivators for beginners who are just making their first bite of new knowledge fruit. The same thing goes with learning a new language. You can start with grammar and slowly build words repository, or you can go with a “naive” approach and simply start speaking. Native speaking girlfriend or boyfriend can accelerate learning of new language faster than any teacher ??. The key concept is to learn the most common phrases and complete sentences and with time master the whole language. It is in nutshell the same learning experience and method that we all had when we learn to use language in the first years of our life. Rules for spelling and grammar will follow in the future one day.
So, we want to learn a new programing language and you want to see some tangible results for your effort. A new application that will be made by you will be a great motivator for further learning. Problem with a traditional approach, and something that educators often fail to understand, is that motivation level will drop down if the invested time and effort is not rewarded with the result. Starting with language syntax and core concepts of programing language will prolong time to make something useful. “Hello World” kind of app will not be good enough to boost motivation for the beginner in any programming language. Anyhow, all the above mentioned is my personal experience and now I will not elaborate it anymore. It is much better to start coding something useful in a “na?ve” way.
Let’s start!
***
My assumption is that you are a total beginner in Python and that you are using the Microsoft Windows environment. Just to mention that switch to Linux is very easy since Python is an almost fully multiplatform language.
***
Step 1: Set your Python development environment
a) Install Python on your Windows machine
- go to the https://www.python.org/downloads/windows/ to get Latest Python 3 Release and download the windows installer (e.g. Windows x86-64 executable installer)
- run it the installer
- check the option "Add Python 3.x to PATH" on the first screen and click Next
- choose "Customize installation" and on next screen check all options ("Documentation", "pip", "tcl/tk and IDLE", "Python test suite", "py launcher", "for all users..." and click Next
- on the next screen just "Customize install location" (e.g. C:\Python38)
- click Install and wait until it is finished.
- when is finished you can optionally “Disable path length limit” or just click “Close”
b) add Python to Path
For Python commands to be available at the windows command prompt we have to do the following:
- search for "environment variables" term in the windows search
- choose option "Edit the system environment variables" and select "Environment Variables"
- under the "System variables" double click at "Path" item
- in the dialog select option "New" and each time add following entries:
C:\Python38 C:\Python38\Scripts C:\Python38\Lib\site-packages\PyInstaller
- click OK to close all dialogs
c) Install version control - this is OPTIONAL
(and GIT is my choice)
- download GIT version control installer and run it with all default settings
d) Install additional python tools and libraries
(note: this will be used to enable copying of images from clipboard to our app)
- search for "cmd" term in windows search and select "Command Prompt"
- run the following commands:
python -m pip install --upgrade pip
pip install pyinstaller
pip install pillow
e) Install tool (IDE) for your programming needs (PyCharm is my choice)
- download and run installer with all default settings
- finish installation of PyCham and reboot your windows
Step 2: Let's start the project
- start PyCharm for the first time and use default settings
- select "Create new project"
- at "Location" text box enter the following path:
"C:\Users\<put your user name here>\Desktop\MyPython\PyNotePlus"
and this will create a project location on your desktop
- expand the section "Project Interpreter: New Virtualenv environment" and select "Existing interpreter" and click the button with "..."
- The new dialog will open, and you select "System Interpreter" (e.g. C:\Python38\python.exe) and click OK.
- click "Create"
Now you will see your development environment ?? and I hope it is love at first sight.
- on the left side (tree view) right-click at "PyNotePlus" under "Project" and select New -> Python File
- provide Name "PyNotePlus” and press Enter
- here is where the whole program code will be placed:
- get the code from the link below (code for file “PyNotePlus.py” is also added at the end of this tutorial):
https://github.com/nevendujmovic/PyNotePlus/blob/master/PyNotePlus.py
- and copy it and paste the code the right side of the editor window in PyCharm
Review the code! Every line of the code is well documented, and you will have a basic idea of how all works.
- run the App for the first time from PyCharm - right-click at the "PyNotePlus.py" file and choose "Run'PyNotePlus'"
- Python interpreter will do its magic and code will be interpreted in a beautiful desktop application that will pop up in front of all windows.
Ok, it is not the most beautiful application, but it is definitely useful. It is a great utility tool that can be used as an additional clipboard for text and for image pasting. It is useful when you have to compare or copy data between applications. It will stay always on top.
- (optional) you can also add your project to your GIT version control:
VCS -> Import into Version Control -> Create Git Repository... and click OK
Step 3: final touch - package everything in the portable python desktop application
As you may be noticed above, we installed "pyinstaller" tool. Now it is time to use it!
- search for "cmd" term in windows search and select "Command Prompt"
The console window will appear.
- position yourself to the location of your project by writing the following command in the console window:
cd C:\Users\<put your user name here>\Desktop\MyPython\PyNotePlus
- build executable by writing the following command in the console window:
pyinstaller --noconsole --onefile PyNotePlus.py
- open File Explorer on your windows and go to:
"C:\Users\<put your user name here>\Desktop\MyPython\PyNotePlus\dist"
Here you will find your application "PyNotePlus.exe" ready for usage and sharing with your friends. All that is needed to run is packaged into windows executable file.
Ok, that is it!
This is the end of the Python “naive” tutorial. Now you have a full mechanic of building various desktop applications. Please review the code in detail. Every line is an important concept and it will open for you a new level of knowledge.
Enjoy Python!
Author
Neven Dujmovic
***
Full “PyNotePlus.py” code:
# ##################################################################################################################### # ##################### by Neven Dujmovic March 2020 - Utility desktop tool - tkinter Python ########################## # ##################################################################################################################### import os from tkinter import * import tkinter as tk import tkinter.font as tk_font from tkinter import filedialog as fd from tkinter import ttk from tkinter import messagebox from PIL import ImageTk, ImageGrab # for Windows environment # import pyscreenshot as ImageGrab # for Linux environment # from PIL import ImageTk # for Linux environment # region ========== Global variables & settings ========== # # initialize tkinter, with creation of Tk root widget (basic window, title bar as defined by OS window manager) root = Tk() # # set default font attributes and assign it to global object "font_style" font_style = tk_font.Font(family="Courier New", size=10) # # set title root.title("Process text (developed by Neven Dujmovic)") # # set geometry (width x height + x_offset + y_offset) root.geometry("820x400+300+200") # # in case you want to make form not resizable just uncomment line below # form.resizable(0, 0) # # place tkinter window on top of the others root.attributes('-topmost', True) root.update() # # lets make "parent" TAB control by using tkinter.Notebook widget (https://wiki.tcl-lang.org/page/tkinter.Notebook) # # widget manages a collection of child windows and displays a single one at a time.. tab_parent = ttk.Notebook(root) # endregion # region =================== Tab 1 ======================= # # First we will make few functions. Those are small code routines made for specific purpose and that will be linked # # with actions (events) triggered by objects (buttons on window dialog in this case) # # this function is used to open text file and load its content to text box widget def open_text_file(): # # ensure error handling in case text file is NOT selected try: # # open select file dialog and assign full path to variable name name = fd.askopenfilename() # # open text file for reading f = open(name, "r") # # read all lines in the file with method "read" # # variable "lines" is a list that will contain all lines in the file lines = f.read() txt_main.insert(tk.END, lines) # # close the file after reading the lines. f.close() # # just for the test - print selected file path in console print(name) except: # # for now you can just ignore "PEP 8: do not use bare 'except' - Too broad exception clause" # # in case of error show message with tkinter "messagebox" object messagebox.showinfo(message="Text file not selected.") # # every call of this function will increase font size by 2 in the txt_main object (of tk.Text type) def increase_text_font(): # # assign "size" attribute to a variable font_size = font_style['size'] # # set new "size" to global object "font_style" font_style.configure(size=font_size + 2) # # every call of the function will decrease font size by 2 in the txt_main object (of tk.Text type) def decrease_text_font(): # # assign "size" attribute to a variable font_size = font_style['size'] # # set new "size" to global object "font_style" font_style.configure(size=font_size - 2) # # new "child" TAB control will be created (tab1) and added to parent TAB control (tab_parent) tab1 = ttk.Frame(tab_parent) tab_parent.add(tab1, text="Text operations") # # frame will be created to serve as a container for button controls frame_topTab1 = Frame(tab1) frame_topTab1.pack(fill=BOTH) # # the tkinter button widget "btnOpenFile" will be used to trigger function "open_text_file" btn_openFile = tk.Button(frame_topTab1, text='File Open', bd='5', command=open_text_file) btn_openFile.pack(side=LEFT, padx=10, pady=5, anchor='ne') # # the tkinter button widget "btnTextSizeIncrease" will be used to trigger function "increase_text_font" btn_textSizeIncrease = tk.Button(frame_topTab1, text='+', bd='5', command=increase_text_font) btn_textSizeIncrease.pack(side=RIGHT, padx=20, pady=5, anchor='ne') # # the tkinter button widget "btnTextSizeDecrease" will be used to trigger function "decrease_text_font" btn_textSizeDecrease = tk.Button(frame_topTab1, text='-', bd='5', command=decrease_text_font) btn_textSizeDecrease.pack(side=RIGHT, padx=0, pady=5, anchor='ne') # # tkinter text widget "txt_main" is added to "child" TAB control (tab1). This is place where text file will be loaded. # # Here we can adjust dimension and background color of text widget and assign previously defined # # global object "font_style". Any change (e.g. font size) in "font_style" will be directly applied to "text_main". txt_main = tk.Text(tab1, height=20, width=100, bg='#FFE4E1', font=font_style) # # this will ensure that all controls will be adjusted as we resize window dialog. txt_main.pack(side=LEFT, fill=BOTH, expand=YES, padx=10, pady=10, anchor='e') # # vertical scrollbar will be added and associated with text widget "txt_main" y_scrollbar = Scrollbar(tab1, orient=VERTICAL, command=txt_main.yview) y_scrollbar.pack(side=RIGHT, fill=Y) txt_main["yscrollcommand"] = y_scrollbar.set # endregion # region =================== Tab 2 ======================= # # this function is used to pass image data from clipboard to dialog window def get_image(): try: temp_path = "some_image.gif" # path to file where image will be temporally stored im = ImageGrab.grabclipboard() # get image from windows clipboard # im = ImageGrab.grab() # get image from linux clipboard im.save(temp_path) # save image to temp file load_for_label = ImageTk.PhotoImage(file=temp_path) # load image from temp file lbl_image.config(image=load_for_label) # set image to tkinter label widget lbl_image.image = load_for_label # save reference to image in memory lbl_image.clipboard_clear() # clear clipboard os.remove(temp_path) # delete temp file except: # # error will occur if clipboard is empty. Show message with tkinter "messagebox" object. messagebox.showinfo(message="Clipboard is Empty.") # # new "child" TAB control will be created (tab2) and added to parent TAB control (tab_parent) tab2 = ttk.Frame(tab_parent) tab_parent.add(tab2, text="Image operations") # # frame will be created to serve as a container for button control frame_topTab2 = Frame(tab2) frame_topTab2.pack(fill=BOTH) # # the tkinter button widget "btn_image" will be used to trigger function "get_image" btn_image = tk.Button(frame_topTab2, text="Paste image", command=get_image) btn_image.pack(side=RIGHT, padx=20, pady=5, anchor='ne') # # the tkinter label widget "lbl_image" is used to display image from clipboard lbl_image = tk.Label(tab2, width=82) lbl_image.pack(side=LEFT, fill=BOTH, expand=YES, padx=10, pady=10, anchor='e') # endregion # back to normal tkinter window # form.attributes('-topmost', False) # # pack() method organizes the widgets in blocks before placing in the parent widget tab_parent.pack(expand=1, fill='both') # # method mainloop() is used when your application is ready to run. # # mainloop() is an infinite loop used to run the application, wait for an event to occur and # # process the event as long as the window is not closed root.mainloop()
Assistant Quality Manager at ATIR d.o.o.
4 年Bravo kolega! Odli?no si ovo napravio