python - 将字符串传递给函数时出现问题

标签 python pyqt5

我正在使用 pyqt5 为我的 python 文件创建一个小型 GUI(我希望稍后将其转换为 .exe 文件)。 我创建了一个非常简单的 GUI,用户在其中选择一个日期,然后单击一个按钮,该按钮将运行传递所选日期的函数。 然而,我似乎无法让它工作 - 我确信有一个简单的修复,但我的谷歌搜索似乎没有工作。

这是我目前的代码:

#MainWindow
class GUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setup()

    def setup(self):
        # window settings
        self.setWindowTitle('Create scheule')
        self.resize(505, 556)

        # Date select settings
        calendarWidget = QtWidgets.QCalendarWidget(self)
        calendarWidget.setGeometry(QtCore.QRect(50, 160, 392, 236))        
        calendarWidget.clicked[QtCore.QDate].connect(self.showDate)

        self.lbl = QLabel(self)
        date = calendarWidget.selectedDate()
        self.lbl.setText(date.toString("MM/dd/yyyy"))
        self.lbl.move(20, 20)

        # create schedule button settings
        cleaned_date = date.toString("MM/dd/yyyy")
        Create_schedule = QtWidgets.QPushButton('Create schedule',self)
        Create_schedule.setGeometry(QtCore.QRect(120, 460, 261, 61))        
        Create_schedule.clicked.connect(self.create_schedule)


    def showDate(self, date):
        self.lbl.setText(date.toString("MM/dd/yyyy"))
        cleaned_date = date.toString("MM/dd/yyyy")
        print(cleaned_date)

    def create_schedule(self, cleaned_date):

        print(cleaned_date)
        creating_schedules(cleaned_date)

        print('created it :D')

if __name__ == '__main__':
    app = QApplication(sys.argv)

    gui = GUI()
    gui.show()

    sys.exit(app.exec_())

GUI 将打开并选择日期(我使用 showDate 函数来检查它是否以我需要的格式创建了一个字符串)。但是,当我运行从另一个文件导入的函数:create_schedules(cleaned_date) 时,它会尝试运行该函数,但它传递的“cleaned_date”值是 bool 值:False。我希望它传递的字符串与设置中创建的字符串相同 - 我不确定为什么它将字符串更改为 False。

我还尝试将 clean_date 移至 create_schedule 中,但这出现了相同的错误。

非常感谢任何帮助,谢谢!

最佳答案

你必须基本上改变两件事:

   # Date select settings
        calendarWidget = QtWidgets.QCalendarWidget(self)
        calendarWidget.setGeometry(QtCore.QRect(50, 160, 392, 236))
        calendarWidget.clicked[QtCore.QDate].connect(self.showDate)
        ########## CHANGE HERE!
        self.calendar_widget = calendarWidget # this line is new

 def create_schedule(self, cleaned_date):
        cleaned_date = self.calendar_widget.selectedDate().toString("MM/dd/yyyy")
        print(cleaned_date)
        #creating_schedules(cleaned_date)

        print('created it :D')

问题是您的按钮不知道日历小部件。所以它不会将日历的值传递给函数create_schedule。

关于python - 将字符串传递给函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57698328/

相关文章:

python - 使用 xpath/lxml 抓取文本

python - Pyqt5 根据自定义小部件中的事件刷新/更新 QListWidget?

python - 创建 QDialog 的 PyQt 单元测试

python - QtWebEngine 拦截带有自定义 URL 模式服务回复的请求

python - 你能检查一下 Python 中的 doctest 是否引发了异常吗?

python - 在 python 中使用 re 删除 unicode 表情符号

python - 单击 Windows 'X'(关闭)按钮时停止任何循环

python - 如何将QLineEdit添加到QMessageBox PyQt5

python - 在 PyTorch 中创建具有多个 channel 的简单一维 CNN

python - 导入Python文件和导入*同一文件的区别