PyQt5每天必学之日历控件QCalendarWidget

yipeiwu_com6年前Python基础

QCalendarWidget 是日历控件。它允许用户以简单和直观的方式选择日期。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
PyQt5 教程

这个例子使用QCalendarWidget控件创建了一个日历。

作者:我的世界你曾经来过
博客:http://blog.csdn.net/weiaitaowang
最后编辑:2016年8月4日
"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QCalendarWidget, QLabel
from PyQt5.QtCore import QDate

class Example(QWidget):

 def __init__(self):
 super().__init__()

 self.initUI()

 def initUI(self):

 cal = QCalendarWidget(self)
 cal.setGridVisible(True)
 cal.move(20, 20)
 cal.clicked[QDate].connect(self.showDate)

 self.lb1 = QLabel(self)
 date = cal.selectedDate()
 self.lb1.setText(date.toString())
 self.lb1.move(130, 260)

 self.setGeometry(300, 300, 350, 300)
 self.setWindowTitle('日历控件') 
 self.show()

 def showDate(self, date):

 self.lb1.setText(date.toString())

if __name__ == '__main__':

 app = QApplication(sys.argv)
 ex = Example()
 sys.exit(app.exec_())

这个例子有一个日历控件和一个标签控件。当前选定的日期用标签显示。

cal = QCalendarWidget(self)

使用 QCalendarWidget 创建日历控件

cal.clicked[QDate].connect(self.showDate)

如果我们在日历控件中选择一个日期,clicked[QDate]信号将连接到用户定义的showDate()方法。

def showDate(self, date):
    self.lb1.setText(date.toString())

我们通过调用selectedDate()方法检索选定的日期。然后我们将Date对象转换成字符串并显示在标签控件中。

程序执行后

这里写图片描述

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Pycharm+django2.2+python3.6+MySQL实现简单的考试报名系统

Pycharm+django2.2+python3.6+MySQL实现简单的考试报名系统

1 准备工作 1.1 环境搭建 1.1.1 安装python3.6 python安装官网 1.1.2 安装django2.2 pip install django(==2.2.0) //...

Python中的异常处理学习笔记

Python 是面向对象的语言,所以程序抛出的异常也是类。 常见的异常类 1.NameError:尝试访问一个没有申明的变量 2.ZeroDivisionError:除数为 0 3.Sy...

python中seaborn包常用图形使用详解

python中seaborn包常用图形使用详解

seaborn包是对matplotlib的增强版,需要安装matplotlib后才能使用。 所有图形都用plt.show()来显示出来,也可以使用下面的创建画布 fig,ax=plt...

python日期相关操作实例小结

本文实例讲述了python日期相关操作。分享给大家供大家参考,具体如下: 用 Python 做项目时,经常会遇到与日期转换相关,日期计算相关的功能,动不动就要去查python手册,感觉麻...

Python 读写文件和file对象的方法(推荐)

1.open 使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。 file_object = open('the...