用QT5 做一个简易的计算器界面,直接上代码:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLineEdit, QPushButton
class calc(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("计算器")
# 数字按钮
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+',
'C','Exit','click me'
]
# 创建数字按钮和输入框
grid = QGridLayout()
self.display = QLineEdit()
grid.addWidget(self.display, 0, 0, 1, 4)
row = 1
col = 0
for button_text in buttons:
button = QPushButton(button_text)
button.clicked.connect(self.buttonClicked)
grid.addWidget(button, row, col)
col += 1
if col > 3:
col = 0
row += 1
self.setLayout(grid)
def buttonClicked(self):
button = self.sender()
text = button.text()
if text == '=':
try:
result = str(eval(self.display.text()))
self.display.setText(self.display.text() + text + result)
except:
self.display.setText("Error")
elif text == 'C':
self.display.setText('') # 清空输入框
elif text == 'Exit':
self.close() # 关闭窗口
elif text == 'click me':
self.display.setText('you are handsome!')
else:
self.display.setText(self.display.text() + text)
if __name__ == '__main__':
app = QApplication(sys.argv)
calc = calc()
calc.show()
sys.exit(app.exec_())
一、代码说明:
- 导入库: 导入
sys
和PyQt5.QtWidgets
模块。 - 创建主窗口类: 创建
Calculator
类,继承自QWidget
,作为计算器主窗口。 - 初始化界面:
- 设置窗口标题为 "计算器"。
- 创建一个
QGridLayout
用于布局。 - 创建一个
QLineEdit
作为显示输入和结果的文本框。 - 创建一个列表
buttons
,包含所有按钮的文本。 - 使用循环遍历
buttons
列表,创建每个按钮并连接其clicked
信号到buttonClicked
方法。 - 将按钮和文本框添加到
QGridLayout
中。
- 按钮点击事件:
buttonClicked
方法处理按钮点击事件。- 获取点击按钮的文本。
- 如果是 "=" 按钮,则使用
eval()
函数计算表达式结果,并显示在文本框中。 - 否则,将按钮文本添加到文本框中。
- 运行程序:
- 创建 `` 对象。
- 创建
Calculator
对象。 - 显示计算器窗口。
- 启动事件循环。
运行结果: