18

I have a problem with my PyQt button action. I would like to send a String with the Function but I got this Error:

TypeError: argument 1 has unexpected type 'NoneType'

import sys

from PyQt5.QtWidgets import QApplication, QPushButton, QAction
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtGui import *
from PyQt5.uic import *

app = QApplication(sys.argv)
cocktail = loadUi('create.ui')

def mixCocktail(str):
      cocktail.show()
      cocktail.showFullScreen()
      cocktail.lbl_header.setText(str)


widget = loadUi('drinkmixer.ui')

widget.btn_ckt1.clicked.connect(mixCocktail("string"))

widget.show()
sys.exit(app.exec_())
CDspace
  • 2,639
  • 18
  • 30
  • 36
Darkdrummer
  • 301
  • 1
  • 2
  • 8
  • What line is this error showing up on? – user3030010 Dec 05 '16 at 20:14
  • Traceback (most recent call last): File "------\drinkmixer.py", line 27, in widget.btn_ckt1.clicked.connect(mixCocktail("string")) TypeError: argument 1 has unexpected type 'NoneType' – Darkdrummer Dec 05 '16 at 20:16
  • Ah. That's because you aren't returning anything from `mixCocktail()`. – user3030010 Dec 05 '16 at 20:19
  • 7
    From looking at some example online, it looks like it expects a callable function. In which case you should replace that argument with `lambda: micCocktail("string")` – user3030010 Dec 05 '16 at 20:20
  • Thank you very much! Now it works – Darkdrummer Dec 05 '16 at 20:22
  • If you ever need to do that with a multi-arguments function, lambda won't work but you can use the `partial` library and connect your signal and function like so: `.connect(partial(my_function, arg1=..., arg2=...))` – Guimoute Mar 04 '19 at 10:24

2 Answers2

25

As suggested by user3030010 and ekhumoro it expects a callable function. In which case you should replace that argument with lambda: mixCocktail("string") AND ALSO don't use str it's a python built-in datatype I have replaced it with _str

import sys

from PyQt5.QtWidgets import QApplication, QPushButton, QAction
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtGui import *
from PyQt5.uic import *

app = QApplication(sys.argv)
cocktail = loadUi('create.ui')

def mixCocktail(_str):
      cocktail.show()
      cocktail.showFullScreen()
      cocktail.lbl_header.setText(_str)
      

widget = loadUi('drinkmixer.ui')

widget.btn_ckt1.clicked.connect(lambda: mixCocktail("string"))

widget.show()
sys.exit(app.exec_())

More about lambda functions: What is a lambda (function)?

tyrudani
  • 3
  • 3
harshil9968
  • 3,254
  • 1
  • 16
  • 26
2

instead of this

widget.btn_ckt1.clicked.connect(mixCocktail("string"))

write

widget.btn_ckt1.clicked.connect(lambda:mixCocktail("string"))