head
è un comando dei sistemi Unix e Unix-like, che mostra sullo standard output le prime linee di uno o più file di testo.
Con il comando head
è possibile stabilire da quando tempo la distribuzione è stata installata sul PC in uso:
head -n1 /var/log/pacman.log
L’output del comando informa che la distro è stata installata il 17 gennaio di quest’anno.
Il codice Python
qui proposto sfrutta le librerie grafiche QtPy5
, per generare un QrCode.
Vediamo, dapprima, la struttura del programma in Qt Designer
:
Sia al bottone (pB_genera
) che alla QLineEdit (lE_testo
) è stato associato il metodo pB_valutaClick
() della classe Ui(QWidget)
. La classe Ui(QWidget)
è così costruita:
class Ui(QWidget):
def __init__(self):
super().__init__()
uic.loadUi('qrcode.ui', self)
self.setFixedSize(500, 390)
def pB_valutaClick(self):
try:
# String which represents the QR code
s = (self.lE_testo.text())
# output file name
filename = "qrcode.png"
filename_svg = "qrcode.svg"
# Generate QR Code
img = pyqrcode.create(s)
img.png(filename, scale=7)
if self.cB_svg.isChecked():
img.svg(filename_svg, scale=8)
pixmap = QPixmap(filename)
self.lab_output.setPixmap(pixmap)
except:
print('Valore nel campo non accettato')
Il codice provvede a costruire l’oggetto window
, istanza della classe Ui()
, attraverso l’istruzione:
app = QApplication(sys.argv)
window = Ui()
window.show()
sys.exit(app.exec())
Si è scelto di dare la possibilità di salvare il qrcode generato anche in formato .svg allorquando il QcheckBox
, nominato cB_svg
, risulta essere flaggato:
if self.cB_svg.isChecked():
img.svg(filename_svg, scale=8)
Qui è possibile recuperare il codice del progetto completo.
Conor McGregor ha picchiato Facchinetti senza un motivo. Quando ce ne sarebbero tantissimi.
La formula di Eulero dà origine ad un’identità considerata tra le più affascinanti della matematica, nota come identità di Eulero, che mette in relazione tra loro cinque simboli che sono alla base dell’analisi matematica: e, i, π, 0, 1…
The following code walks you through the steps to create an empty GUI window.
# basic_window.py
# Import necessary modules
import sys
from PyQt5.QtWidgets import QApplication, QWidget
class EmptyWindow(QWidget):
'''
Create a new class, EmptyWindow, which inherits from other PyQt modules,
in this case from the QWidget class.
Inheriting from QWidget means we have access to all the attributes
to create GUIs using PyQt, but we also can add our own variables and
methods in our new class.
'''
def __init__(self):
super().__init__()
'''
create default constructor for QWidget; super is used to access methods
from parent class
'''
self.initializeUI()
def initializeUI(self):
"""
Initialize the window and display its contents to the screen.
"""
self.setGeometry(100, 100, 400, 300)
self.setWindowTitle('Empty Window in PyQt')
self.show()
# Run program
if __name__ == '__main__':
app = QApplication(sys.argv) # Create instance of QApplication class
window = EmptyWindow() # Create instance of EmptyWindow class
sys.exit(app.exec_()) # Start the event loop
Your initial window should look similar to the one in the following figure depending upon your operating system.
Walking through the code, we first start by importing the sys
and PyQt5 modules that we need to create a window. We commonly use sys
in order to pass command-line arguments to our applications and to close them.
The QtWidgets
module provides a set of UI (User Interfaces) elements that can be used to create desktop-style GUIs. From the QtWidgets
module, we import two classes, QApplication
and QWidget
. You only need to create a single instance of the QApplication
class, which manages the application’s main event loop, flow, initialization, and finalization, as well as session management.
Take a quick look at
app = QApplication(sys.argv)
QApplication
takes as an argument sys.argv
. You can also pass in an empty list if you know that your program will not be taking any command-line arguments using
app = QApplication([])
Next we create a window object that inherits from the class we created, EmptyWindow
. Our class actually inherits from QWidget
, which is the base class for which all other user interface objects are derived.
We need to call the show()
method on the window object to display it to the screen.
This is located inside the initializeUI()
function in our EmptyWindow
class. You will notice app.exec_()
in the final line of the program. This function starts the event loop and will remain here until you quit the application. sys.exit()
ensures a clean exit.
If all of this is a little confusing as to why we have to create an application before
we create the window, think of QApplication
as the frame that contains our window.
The window, our GUI, is created using QWidget
. Before we can create our GUI, we must create an instance of QApplication
that we can place window in.
Modifying the Window
The preceding EmptyWindow
class contains a function, initializeUI()
, that creates the window based upon the parameters we specify.
setGeometry()
defines the location of the window on your computer screen and
its dimensions, width and height. So the window we just started is located at x=100
,y=100
in the window and has width=400
and height=300
. setWindowTitle()
is used to change the title of our window.
Python is an object-oriented programming language. The key notion is that of an object. An object consists of two things: data and functions (called methods) that work with that data. As an example, strings in Python are objects. The data of the string object is the actual characters that make up that string. The methods are things like lower
, replace
, and split
. In Python, everything is an object. That includes not only strings and lists, but also integers, floats, and even functions themselves.
Creating your own classes.
A class is a template for objects. It contains the code for all the object’s methods.
Here is a simple example to demonstrate what a class looks like. It does not
do anything interesting.
class Esempio:
def __init__(self, a,b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
e = Esempio(8,6)
print(e.add())
To create a class, we use the class
statement. Class names usually start with a capital.
Most classes will have a method called __init__
. The underscores indicate that it is a special kind of method. It is called a constructor, and it is automatically called when someone creates a new object from your class. The constructor is usually used to set up the class’s variables. In the above program, the constructor takes two values, a
and b
, and assigns the class variables a
and b
to those values.
The first argument to every method in your class is a special variable called self
. Every time your class refers to one of its variables or methods, it must precede them by self
. The purpose of self
is to distinguish your class’s variables and methods from other variables and functions in the program.
To create a new object from the class, you call the class name along with any values that you want to send to the constructor. You will usually want to assign it to a variable name. This is what the line e=Esempio(8,6)
does.
To use the object’s methods, use the dot operator, as in e.add()
.
Here is a class called Analyzer
that performs some simple analysis on a string. There are methods to return how many words are in the string, how many are of a given length, and how many start with a given string.
from string import punctuation
class Analizza:
def __init__(self, s):
for c in punctuation:
s = s.replace(c,'')
s = s.lower()
self.parole = s.split()
def numeri_di_parole(self):
return len(self.parole)
def inizia_con(self,s):
return len([w for w in self.parole if w[:len(s)]==s])
def numero_di_lunghezza(self, n):
return len([w for w in self.parole if len(w)==n])
s = 'Tanto va la gatta al lardo che ci lascia lo zampino'
analizzatore = Analizza(s)
print(analizzatore.parole)
print('Numero di lettere:', analizzatore.numeri_di_parole())
print('Numero di parole che iniziano con la "c":', analizzatore.inizia_con('c'))
print('Numero di parole formato da due lettere:', analizzatore.numero_di_lunghezza(2))
A few notes about this program:
- One reason why we would wrap this code up in a class is we can then use it a variety of different programs. It is also good just for organizing things. If all our program is doing is just analyzing some strings, then there’s not too much of a point of writing a class, but if this were to be a part of a larger program, then using a class provides a nice way to separate the
Analizza
code from the rest of the code. It also means that if we were to change the internals of theAnalizza
class, the rest of the program would not be affected as long as the interface, the way the rest of the program interacts with the class, does not change. Also, theAnalizza
class can be imported as-is in other programs. - The following line accesses a class variable:
print(analizzatore.parole)
.
You can also change class variables. This is not always a good thing. In some cases this is convenient, but you have to be careful with it. Indiscriminate use of class variables goes against the idea of encapsulation and can lead to programming errors that are hard to fix. Some other object-oriented programming languages have a notion of public and private variables, public variables being those that anyone can access and change, and private variables being only accessible to methods within the class. In Python all variables are public, and it is up to the programmer to be responsible with them. There is a convention where you name those variables that you want to be private with a starting underscore, like _var1
. This serves to let others know that this variable is internal to the class and shouldn’t be touched.
Inheritance
In object-oriented programming there is a concept called inheritance where you can create a class that builds off of another class. When you do this, the new class gets all of the variables and methods of the class it is inheriting from (called the base class). It can then define additional variables and methods that are not present in the base class, and it can also override some of the methods of the base class. That is, it can rewrite them to suit its own purposes. Here is a simple example:
class Parent:
def __init__(self, a):
self.a = a
def method1(self):
return self.a*2
def method2(self):
return self.a+'!!!'
class Child(Parent):
def __init__(self, a, b):
self.a = a
self.b = b
def method1(self):
return self.a*7
def method3(self):
return self.a + self.b
p = Parent('hi')
c = Child('hi', 'bye')
print('Parent method 1: ', p.method1())
print('Parent method 2: ', p.method2())
print()
print('Child method 1: ', c.method1())
print('Child method 2: ', c.method2())
print('Child method 3: ', c.method3())
We see in the example above that the child has overridden the parent’s method1
, causing it to now repeat the string seven times. The child has inherited the parent’s method2
, so it can use it without having to define it. The child also adds some features to the parent class, namely a new variable b
and a new method, method3
.
A note about syntax: when inheriting from a class, you indicate the parent class in parentheses in the class
statement.
If the child class adds some new variables, it can call the parent class’s constructor as demonstrated below. Another use is if the child class just wants to add on to one of the parent’s methods. In the example below, the child’s print_var
method calls the parent’s print_var
method and adds an additional line.
class Parent:
def __init__(self, a):
self.a = a
def print_var(self):
print("The value of this class's variables are:")
print(self.a)
class Child(Parent):
def __init__(self, a, b):
Parent.__init__(self, a)
self.b = b
def print_var(self):
Parent.print_var(self)
print(self.b)
Note – You can also inherit from Python built-in types, like strings (str
) and lists (list
), as well as any classes defined in the various modules that come with Python.
Note – Your code can inherit from more than one class at a time, though this can be a little tricky.
Oscurato il sito di Forza Nuova. Ton sur ton.
Il pretesto è quello di creare un programmino per scorporare l’iva dal totale della fattura. Useremo Python
e PyQt6
per creare un’interfaccia grafica al semplice programma. Qui, il repository da cui prelevare i sorgenti.
Al pulsante pB_calcola
colleghiamo il signal pB_valutaClick()
quando si verifica l’evento clicked()
.
Di seguito il codice:
#!/usr/bin/python
from PyQt6.QtWidgets import QApplication, QWidget
from PyQt6 import uic
class Ui(QWidget):
def __init__(self):
super().__init__()
uic.loadUi('imponibile.ui', self)
self.setFixedSize(399, 177)
def pB_valutaClick(self):
try:
n1 = float(self.lE_totFattura.text())
n2 = float(self.lE_aliquota.text())
n3 = n1*100/(n2+100)
n4 = n1-n3
self.lE_imponibile.setText(str(format(n3,'>12.2f')))
self.lE_iva.setText(str(format(n4,'>12.2f')))
self.l_errore.setText('')
except:
self.l_errore.setText('Valore numerico non accettato')
self.lE_imponibile.setText('')
self.lE_iva.setText('')
self.lE_aliquota.setText('22')
app = QApplication([])
window = Ui()
window.show()
app.exec()
Lo screencast seguente mostra il funzionamento del programma: