Python pyqt5在界面显示当前日期时间,代码注释要详细
时间: 2023-08-11 20:17:05 浏览: 105
好的,下面是一个简单的 Python Pyqt5 代码示例,用于在界面上显示当前的日期和时间,注释详细:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtCore import QTimer, QDateTime
class DateTimeApp(QWidget):
def __init__(self):
super().__init__()
# 设置窗口大小和标题
self.setGeometry(100, 100, 400, 200)
self.setWindowTitle("Date Time App")
# 添加标签用于显示日期和时间
self.date_label = QLabel(self)
self.time_label = QLabel(self)
# 创建垂直布局
layout = QVBoxLayout()
# 将标签添加到布局中
layout.addWidget(self.date_label)
layout.addWidget(self.time_label)
# 设置布局
self.setLayout(layout)
# 定时器用于实时更新时间
timer = QTimer(self)
timer.timeout.connect(self.update_time)
timer.start(1000)
# 显示窗口
self.show()
def update_time(self):
# 获取当前日期时间并更新标签
current_time = QDateTime.currentDateTime()
current_date = current_time.toString("yyyy-MM-dd")
current_time = current_time.toString("hh:mm:ss")
self.date_label.setText(current_date)
self.time_label.setText(current_time)
if __name__ == "__main__":
app = QApplication(sys.argv)
date_time_app = DateTimeApp()
app.exec_()
```
这段代码使用了 PyQt5 库来创建 GUI 程序,并通过 QDateTime 类获取实时日期时间信息。其中,`update_time` 方法用于获取当前日期时间并更新标签。定时器每秒都会调用 `update_time` 方法,以实现实时更新时间的效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)