Оcenka-BEL.com - безплатни онлайн тестове, пробни изпити, видео уроци и помощ при писане на задания от литературно и хуманитарно естество

Creating your first desktop app with Python

Публикувано: 2018-09-29 17:46:17

Python enables developers to craft desktop applications. In this tutorial, we are going to create a desktop app in Python and make an executable for Windows. The application is going to be simple – it would allow users to select an article from a list, click read and the article will open in their browser. We are going to use Tkinter to craft the GUI that our application needs.
Creating your first desktop app with Python

Our application imports the following modules:

 

 

 

1

2

3

4

from Tkinter import *

import webbrowser

import os

import data

 

 

Data is our own module (file) which contains a list with dictionaries which define titles of articles and URLs where they can be found.

The data module looks like that:

 

 

 

1

2

3

4

5

6

7

articleList = [

{‘name’: “An overview of Laravel 5 Facades through the Session and Auth facades”,

‘url’: “https://www.phpgang.com/an-overview-of-laravel-5-facades-through-the-session-and-auth-facades_3645.html”

},

{‘name’: “Creating a Simple Plagiarism Checker in Node.js”,

“url”: “https://www.phpgang.com/creating-a-simple-plagiarism-checker-in-node-js_3529.html”},

....

 

 

Webbrowser allows to open the user’s browser to different websites and the os module contains utility methods such as a method that allows us to join paths in a OS-independent way or get the OS name.

 

 

 

1

2

3

4

5

6

7

8

class Reader(Frame):

 

def __init__(self, master=None):

Frame.__init__(self,master)

self.pack()

self.articleList = data.articleList

self.readingInformation = None

self.createWidgets()

 

 

We create a class called Reader which accepts the Tkinter’ sframe and create the __init__ method which works like PHP’s __constructand it allows us to run logic whenever our class is instantiated.

In it, we set some properties that the class will have. articleList would contain the data that we want to show in the app and readingInformation would contain a message that is shown to users when they open up an article. Afterwards, we call the createWidgetsmethod on our class.

The createWidgets method loops over the list with dictionaries and creates a new list which contains only the title (name) of each article. Then, it creates a variable called optionSelected which will hold the title of the article that is currently selected by the user and initializes it to the first article in the list.

Afterwards, an OptionMenu UI is created and we pass it the variable from which we would retrieve selected options and we also pass it the unpacked list of articles which would be added as options. We set the OptionMenu to have a green background and pack it. Then, we create a Button UI, set its text, foreground (text color), background and provide a callback which will be executed when the button is clicked with the help of the command key. In our case, the readArticle method of the Reader class will be executed. Finally,  we create a Label UI which will just be some text at the bottom of the window. The second parameter called  textvariable would allow us to change the text of the label anywhere in our application logic.  Then, we set the font family to Arial and the font size to 16 with the help of the font key. Finally, we set the foreground to a hexadecimal color and pack the label.

 

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

def createWidgets(self):

articleNamesOnly = []

for x in self.articleList:

articleNamesOnly.append(x[‘name’])

self.optionSelected = StringVar(self.master)

self.optionSelected.set(articleNamesOnly[0])  # initial value

option = OptionMenu(self.master, self.optionSelected, *articleNamesOnly)

option[‘bg’] = “green”

option.pack()

readBtn = Button(self)

readBtn[“text”] = “Read”

readBtn[“fg”] = “white”

readBtn[‘bg’] = “crimson”

readBtn[“command”] = self.readArticle

readBtn.pack()

self.readingInformation = StringVar()

readingLabel = Label(self.master, textvariable=self.readingInformation)

readingLabel[‘font’] = (“Arial”, “16”)

readingLabel[‘fg’] = “#666”

readingLabel.pack()

 

 

The readArticle method which is executed when the read buton gets clicked just finds the URL of the article that is selected (remember that we have the title of the article saved in our optionSelected property), opens it in the user’s web browser and updates the Label UI’s text.

 

 

 

1

2

3

4

5

6

7

8

def readArticle(self):

url = “”

for x in self.articleList:

if x[‘name’] == self.optionSelected.get():

url = x[‘url’]

break

self.readingInformation.set(“Reading “ + self.optionSelected.get() + “!”)

webbrowser.open(url)

 

 

Finally, we create our Tkinter app, set the title of the application’s window, add an icon to the application’s window (an image file in the same folder where the current .py file is in)

 

 

 

1

2

3

4

5

6

7

8

root = Tk()

root.wm_title(“Web Development Articles Reader | phpgang.com”)

if “nt” == os.name:

root.wm_iconbitmap(bitmap = “favicon.ico”)

<strong>else</strong>:

root.wm_iconbitmap(bitmap = “@favicon.xbm”)

app = Reader(master=root)

app.mainloop()

 

 

Compling the Python application into an executable for Windows

To make the executable we are going to use pyinstaller. If you have installed Python properly, you just need to run your Terminal and type pip install pyinstaller to get it. Otherwise, you would have to set the path to the Python folder and the path to the Python Scripts folder in your PATH environment variable (something like C:/Python27 and C:/Python27/Scripts for Python 2.7).

Now, you can just browse to the folder where your app is and run pyinstaller.exe FILENAME.py–onefile –icon=favicon.ico to create a single executable file (.exe) from your application. In our case, after it is created we would need to add the two icon files to the directory where the executable is – otherwise they would not be available and the application will crash.

Our application files

Figure 1: Our application files

And, voila, we have made our first desktop application in Python!

The finished articles reader application in Python

Figure 2: The finished  articles reader application in Python

 

Tutorial Categories:

 

 

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.bizfacebooktwitter

ARticle source: https://www.phpgang.com/creating-your-first-desktop-app-with-python_3845.html

-->