Python High-level Usages
Unit 1 GUI Designations
A good application for normal users can’t be without a good frames. (no such people like the black console). So, it’s important to study how to design a good UI frame.
1.1 tkinter Module
tkinter is a built-in module in Python, it’s using Tcl/Tk modules. However, in the real developments, its users is less than Qt’s, so here is only simple destruction below.
1.1.1 Create a Window
# Unit1/1.py
import tkinter
tk = tkinter.Tk()
tk.mainloop()
You can use the script above to create a window. Here we prise it.
Line 1
import tkinter
:import tkinter module
Line 2tk = tkinter.Tk()
: Create a Tk example
Line 3tk.mainloop()
: Go into the main loop
Line 1 to import tkinter module is unnecessary to talk about it more. (You are reading this passage, so I believe your programming skills in Python). Line 2, Tk is a class. As a window class, instance it to get an example. Line 3, call its mainloop
method. mainloop means “main loop”. If you have ever built a window in C language, the code below can’t be strange to you.
while (1) {
switch (msg){
WM_DESTROY:
// TODO: Destroy the window
break;
}
}
This is on Windows environment, to listen to the messages from a registered window. Through a unstoppable loop, keep on listening to messages (msg), use switch keyword (like a long if…elif…else… sentence) to filter the messages and process. WM_DESTROY is the message on destroying windows. Here we call mainloop
method, in order to build this function, if not, the windows will close as soon as it shows, even not show at all.
1.1.2 tkinter Widgets
tkinter defines some useful widgets. Some of them are below:
Widget Name | Belonging to | Description |
---|---|---|
Button | tkinter | Button |
Label | tkinter | Text label |
Scroll | tkinter | Scrollbar |
Spinbox | tkinter.ttk | Number box |
Text | tkinter | Text box |
Below we show an example about Button widget, in order to show its usage.
import tkinter # line 1
tk = tkinter.Tk() # line 2
btn = tkinter.Button( # line 3
master=tk, # line 4
text="Button Text", # line 5
command=lambda: print("Clicked Button"), # line 6
) # line 7
btn.pack() # line 8
tk.mainloop() # line 9
Line 1: Instructed.
Line 2: Instructed.
Line 3: Create a Button widget example.
Line 4: Set argument master. master is the only one argument which can ignore the argument name. Heremaster=
can be ignored. master’s value is the widget’s master box, here it’s tk window.
Line 5: text sets the text on the button.
Line 6: command sets the callback function. It will be called when the button is clicked. It has no arguments.
Line 7: Space symbol, ignored.
Line 8: Call pack method to set the position.
Line 9: Instructed.
There’s nothing can be talked about, except pack method. tkinter defines 3 methods1:
Method Name | Arguments | Description |
---|---|---|
pack | [side] | Position with “blocks” |
grid | row, column | Grid position |
place | x, y | Position in a xOy system |
Attention:
- While using place method, zero point is on the left & top of the window. x, y are towords right and bottom. The unit length is 1dp.
- In one master box, it’s not allowed to use both pack method and grid method.
- In the definitions of position methods, they are all used changeable keyoword argument (
**kwargs
) way, so it’s necessary to use side, x, etc. key name.
1.2 PyQt
1.2.1 PyQt Environment Building
You can use pip tool to install PyQt modules.
pip install PyQt5
Of course, you can also install PySide2 module, it even includes all of PyQt5, and is with tools like designer. designer is a tool in C++ Qt for UI designations, it will save much time during frame designations. While using pip downloading, you can use -i option to set the source mirror. The default mirror’s URL is https://mirror.pypi.org/simple/. This is PyPI’s official website, it updates packages quickly, but it’s too slow to download from it.Attention: Later the program may need PyQtWebEngine as a web engine, so please use pip to install PyQtWebEngine:
pip install PyQtWebEngine
In the past versions PyQtWebKit is available, we can use QWebEngine and QWebView, but QtWebKit is no supported, so we don’t use them.
1.2.2 Create a Window in a Application
Run the module below to show a main window in a Qt application. It uses PySide2.
from PySide2.QtWidgets import *
from PySide2.QtCore import *
import sys
if __name__ == '__main__':
app = QApplication(sys.argv)
main = QMainWindow()
main.show()
sys.exit(app.exec_())
Line 1 to 3: Import modules
Line 4: Empty
Line 5: Main entry of program
Line 6: Create a QApplication application
Line 7: Create a QMainWindow main window
Line 8: Call show method, get ready to show the main window
Line 9: Run the application, and return the application’s returned value to the operating system
Warning: When calling show
method, it gets ready to show the window, but it doesn’t show it until calling exec_
method. This is very important.
1.2.3 Add Widgets
Most of widgets are in module PyQt5.QtWidgets / PySide2.QtWidgets.
Widget Name | Description | Belonging to |
---|---|---|
QCheckButton | Checkable button | QtWidgets |
QCombobox | Drop-down box | QtWidgets |
QDialog | Dialog window | QtWidgets |
QDoubleSpinbox | Floating number (double) box | QtWidgets |
QGroup | Group of widgets | QtWidgets |
QLabel | Text label | QtWidgets |
QMainWindow | Main window | QtWidgets |
QMessagebox | Message window | QtWidgets |
QProgressbar | Progressbar | QtWidgets |
QPushButton | Button | QtWidgets |
QRadioButton | Choosing button | QtWidgets |
QSpinbox | Integer box | QtWidgets |
QStatusbar | Statusbar | QtWidgets |
QTabWidget | Showing on pages | QtWidgets |
QTextArea | Text edition area | Qtwidgets |
QTextBrowser | Text showing area | QtWidgets |
QWebEngineView | Web page | QtWebEngine |
QWidget | Base class of widgets | QtWidgets |
All of widgets are supered class QtWidgets.QWidget:
QWidget.__init__(self, [parent, [**kwargs]])
# Source definition in site-packages:
def __init__(parent=None, **kwargs):
pass
parent belongs to QWidget type, its value is the master widget, the default value is None, as this it’s a main widget. Simple widgets, such as QPushButton, this field must be filled, or throws an error. Here is an example:
from PySide2.QtWidgets import *
from PySide2.QtCore import *
import sys
class MainWindow(QMainWindow):
def __init__(self)
super(MainWindow).__init__(self, parent=None)
self.label = QLabel(self)
self.label.setText("Test text")
self.btn = QPushButton(self)
self.btn.setText("Test Button")
if __name__ == "__main__":
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
This passage includes 3 parts:
First, line 1 to 3: Import modules
Second, line 5 to 11: Define class MainWindow (you can use other class names)
Third: line 13 to 17: Main entry of program
If you have ever used designer to create Python UI script, you found in the script the widgets are defined in a new class named ui_xxx. About usages of designer, the later sections will descripte it.
In my opinion, this is a good way to manage our files. Through creating UI modules, we can divide a large file into UI module and logic module with program entry.
1.2.4 Singles
As we know, PyQt is supported by C++ Qt. Qt uses a new object single. For example, if we click a button, it will throw out a single called clicked. We can connect a single with a function to process while singlw is being throwing out.
Example:
from PySide2.QtWidgets import *
from PySide2.QtCore import *
import sys
import threading
import time
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self, parent=None)
self.btn = QPushButton(self)
self.btn.setObjectName('btn')
self.btn.setText('Test Button')
self.connect_()
def connect_(self):
self.btn.clicked.connect(self.clicked_)
@staticmethod
def clicked_():
print("Button is clicked.")
def disc():
time.sleep(5)
main.btn.disconnect(clicked)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.show()
threading.Thread(
name='Thread - Disconnect',
daemon=True,
target=disc,
).start()
sys.exit(app.exec_())
As the size and lines of file are getting more, so we only talk about some parts of file.
This file includes 2 threads: MainThread and Thread - Disconnect. MainThread is created and started by the Python interpreter (or Python virtual machine) automatically, but Thread - Disconnect is ordered to creat and start by ourselves. MainThread has responsibilities to execute the Qt application and show the window with its widget btn; Thread - Disconnect is to disconnect the callback function and single clicked of the button after 5 seconds from starting Qt application.
So if you run this script, you’ll see a button in a window. In the front 5 seconds, as soon as you click it, you’ll see a line of text in console, but after 5 seconds, this function is disabled. Because when the window is defined, we connect single clicked of the button and the console printing function, but after 5 seconds, in thread Thread - Disconnect, it disconnects them, so then when you click it, the console printing function will not be called.
Summar on Single:
- Throw out during events.
- Use a single’s connect method to connect a single and a callback function.
- Use a single’s disconnect method to disconnect a single and its callback function.
Here are some useful singles. Column Arguments is optional.
Single | When to call | Arguments |
---|---|---|
clicked | be clicked | — |
changed | value changed | — |
foused | get foused | — |
The arguments between a couple of brackets are optional. ↩︎