0%

PyQt6学习第一天——基础框架、信号与槽和第一个计算器程序

基础框架

1
2
3
4
5
6
7
8
9
10
11
12
from PySide6.QtWidgets import QApplication, QWidget

class MyWindow(QWidget):
def __init__(self):
super().__init__()


if __name__ == "__main__":
app = QApplication()
window = MyWindow()
window.show()
app.exec()

第一个计算器程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from PySide6.QtWidgets import QWidget, QApplication
from Ui_Calculator import Ui_Form

class calcWindow(QWidget, Ui_Form):
def __init__(self):
super().__init__()
self.setupUi(self)
self.result = ''
self.bind()

def bind(self):
# 批量为 btn0 到 btn9 添加点击事件
for i in range(10):
button = getattr(self, f'btn{i}')
button.clicked.connect(lambda _, b=button: self.addNumber(b.text()))

# 为运算按钮添加点击事件
operators = {
'btn_multiply': '*',
'btn_divide': '/',
'btn_substract': '-',
'btn_plus': '+'
}

for btn_name, symbol in operators.items():
button = getattr(self, btn_name)
button.clicked.connect(lambda _, s=symbol: self.addNumber(s) if self.isValid() else None)

self.btn_equal.clicked.connect(self.calcResult)
self.btn_clear.clicked.connect(self.clearBox)

def clearBox(self):
self.result = ''
self.result_box.clear()

def calcResult(self):
try:
result = str(eval(self.result))
self.result_box.setText(result)
self.result = result
except ZeroDivisionError:
self.result_box.setText("Cannot divide by zero")
self.result = ''
except Exception as e:
self.result_box.setText("Error")
self.result = ''

def isValid(self):
return self.result_box.text()[-1:].isdigit()

def addNumber(self, num: str):
self.result += num
self.result_box.setText(self.result)

if __name__ == '__main__':
app = QApplication()
window = calcWindow()
window.show()
app.exec()