Ошибка argument 1 has unexpected type nonetype

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's user avatar

CDspace

2,62918 gold badges30 silver badges36 bronze badges

asked Dec 5, 2016 at 20:12

Darkdrummer's user avatar

6

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)?

5

instead of this

widget.btn_ckt1.clicked.connect(mixCocktail(«string»))

write

widget.btn_ckt1.clicked.connect(lambda:mixCocktail(«string»))

answered Apr 8, 2021 at 21:18

damanpreet singh's user avatar

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Closed

mikroled opened this issue

Jan 16, 2021

· 5 comments

Labels

question

Further information is requested

Comments

@mikroled

Due to non working transfers with mks robin wifi firmware 1.0.2 I hopefully flashed the latest firmware 1.0.4. to the device.

Now the transfer is startig in Cura 4.8 but the Error «argument 1 has unexpected type ‘NoneType’ comes up
during the transfer.
The transfer is nevertheless closed and the printer shows the preview of the model, but the Error message «Err2» is shown on the printer TFT and the print job does’t start.

Printer: TwoTrees Sapphire Pro MKS Robin Nano v1.2 with original firmware v2.0

@mikroled

I’ve got it working now by installing the MKS Plugin from here:
https://github.com/makerbase-mks/Software/tree/master/MKS%20Plugin

Now the Plugin View in Cura shows the MKS Plugin Connection twice (verson 1.0.0 grayed out and 1.0.2 active) as shown in the screenshot.
The MKS Wifi Plug is not listet in the Plugin list, but working…
Cura Plugins

Apparently I mixed something up, but it works so far.
Does anyone have any idea what happened and how I can clean it up?

@Jeredian

This thing happens when you have installed the previous version of the plugin manually, or into another folder.
Cura has 2 folders for plugins, one for the plugin from the market place, and another inside the default installation path.

@Jeredian

You can remove both of them, and try the latest from this repository.
The old version that you used doesn’t have support with Cura 4+.
The latest version from this repo supports Cura 4.6. But you can try it out with Cura 4.8 too.
Also, it’s an open-source plugin, feel free to make pull requests to make it better.

@mikroled

Ok guys, I removed all plugins and install only the latest from here. Everting works fine now.

Thank you very much for your help and your work on this plugin.

@Elkin-Vasily

This version of plugin will be in Cura market in a few weeks

Labels

question

Further information is requested

【pyqt5】TypeError: argument 1 has unexpected type ‘NoneType’

self.button.clicked.connect(self.close())

currently usingconnectTimeTypeError: argument 1 has unexpected type 'NoneType'Error, solution:

self.button.clicked.connect(lambda:self.close())

Copyright Complaint      
Spam Report

Intelligent Recommendation

pymatgen api【TypeError: argument of type ‘NoneType‘ is not iterable】

Problem Description Run pymatgen, API produces an error Error: Insert a picture description here answer There are two APIs, one long, one short. Long API:API address Short API:address Linux installati…

PYQT PIL read pictures Argument 1 HAS UNEXPECTED TYPE ‘… imagefile’

First PIL, if you read the picture, you should use To change Image to Pixmap and use Label to display: you can use or But sometimes Argument 1 HAS UNEXPECTED TYPE ‘… ImageFile’ This is because the P…

TensorFlow error TypeError: Fetch argument None has invalid type class ‘NoneType’

The problem with tensorflow running cnn convolutional neural network is as follows: And the first step of the loop is very smooth, starting from the second step to report this error. You can see the p…

Tensorflow reported an error: TypeError: Fetch argument None has invalid type class ‘NoneType’

This error often occurs when using tensorflow, but the reasons are often different. The first situation: In the calculation graph of tensorflow, we can use the function def to encapsulate some tf oper…

TypeError: object of type ‘NoneType’ has no len()

Misuse 1 result…

More Recommendation

TypeError: object of type ‘NoneType‘ has no len()

TypeError: object of type ‘NoneType’ has no len() Reference: https://blog.csdn.net/xumesang/article/details/51221706 In fact, it is because my variable is not a list, and None, that is, th…

[Pyqt5] Argument 1 HAS UNEXPECTD TYPE ‘qpushbutton‘ How to solve

In order to practice the use of the dialog box, I wrote a practice code, as follows After execution, the following error is always prompted: TypeError: addLayout(self, QLayout, stretch: int = 0): argu…

QImage: argument 1 has unexpected type ‘memoryview’ arguments did not match any overloaded call

First error: task: Read the picture through cv2, then intercept a part of it, and display it in Qlabel. process: It is no problem to display the picture read by cv2 directly, the code is as follows: W…

Python pika, TypeError: exchange_declare () got an unexpected keyword argument ‘type’ fixes

Many versions are onlinetype=’fanout’ Such. (This is based on python = 3.6 version, pika = 0.13.0 version) Throw an exception Should:type=’fanout’ Changechange_type=’fanout’…

trnsorflow TypeError: Fetch argument + has invalid type

Sess.run in tensorflow can’t run ordinary constant directly, which is sess.run(2) here….

I get this error on both 2.10 & 2.12 on two different machines running Ubuntu 14.04 with Python 2.7.6.

When trying to run the fixed-distance buffer on a shapefile with polylines I get the following error:

QgsFeature.setGeometry(QgsGeometry): argument 1 has unexpected type 'NoneType' See log for more details

With full trace-back:

Uncaught error while executing algorithm
Traceback (most recent call last):
Traceback (most recent call last):|  
File "/usr/share/qgis/python/plugins/processing/core/GeoAlgorithm.py", line 230, in execute|
self.processAlgorithm(progress)|
File "/usr/share/qgis/python/plugins/processing/algs/qgis/FixedDistanceBuffer.py", line 72, in processAlgorithm|
dissolve, segments)|
File "/usr/share/qgis/python/plugins/processing/algs/qgis/Buffer.py", line 81, in buffering|    outFeat.setGeometry(outGeom)|TypeError: QgsFeature.setGeometry(QgsGeometry): argument 1 has unexpected type 'NoneType'|

The first time I opened the «Processing» log to see more about this error, I noticed a problem with the SAGA installation but fixing that doesn’t seem to solve this problem.

Уведомления

  • Начало
  • » Python для новичков
  • » PyQt5. Передача данных в сигнале

#1 Янв. 4, 2017 02:58:09

PyQt5. Передача данных в сигнале

Здравствуйте.

Не получается сделать передачу данных в сигнале.
Сделал через несколько разных методов. Подскажите как переделать в один метод, что бы в нём передавалось значение через параметр.

Сделано: set_table_size_3, set_table_size_4, set_table_size_5
Хочется: set_table_size(count)

 #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import random
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QGridLayout, QPushButton, QAction
from PyQt5.QtCore import QSize, pyqtSignal, QBasicTimer
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
    def init_ui(self):
        self.m_gridTable_Schulte = OstGridTable(self)   # создание экземпляра класса OstGridTable
        self.setCentralWidget(self.m_gridTable_Schulte)  # назначение таблицы (OstGridTable) центральным виджетом
        main_menu = self.menuBar()                      # создание экземпляра меню (строка меню)
        size_menu = main_menu.addMenu('Задать размер таблицы')
        size_button = QAction('3x3', self)
        size_button.setStatusTip('Создать поле размером 3x3')
        size_button.triggered.connect(self.m_gridTable_Schulte.set_table_size_3)
        size_menu.addAction(size_button)
        size_button = QAction('4x4', self)
        size_button.setStatusTip('Создать поле размером 4x4')
        size_button.triggered.connect(self.m_gridTable_Schulte.set_table_size_4)
        size_menu.addAction(size_button)
        size_button = QAction('5x5', self)
        size_button.setStatusTip('Создать поле размером 5x5')
        size_button.triggered.connect(self.m_gridTable_Schulte.set_table_size_5)
        size_menu.addAction(size_button)
        self.show()                                     # отображаем окно на экране
class OstGridTable(QWidget):
    m_grid_table_schulte = QGridLayout()                # создаём экземпляр класса QGridLayout
    def __init__(self, parent):
        super().__init__(parent)
        self.table_size = 5                             # размерность таблицы
        self.regenOstGridTable()                        # обновляем таблицу
    def regenOstGridTable(self):                        # метод очищает таблицу
        self.delete_buttons()                           # запуск метода delete_buttons()
        names = [names + 1 for names in range(0, self.table_size * self.table_size)]
        random.shuffle(names)                       # перемешивание последовательности
        i = 0
        for j in range(0, self.table_size):
            for k in range(0, self.table_size):
                button = QPushButton(str(names[i]), self)  # создаём экземпляр класса QPushButton
                button.setMinimumSize(QSize(90, 90))  # задаём размер кнопки
                # привязываем сигнал к методу on_button_clicked (используем сигнал clicked)
                # button.clicked.connect(self.on_button_clicked)
                self.m_grid_table_schulte.addWidget(button, j, k)  # добавляем кнопки на раскладку
                i += 1
        self.setLayout(self.m_grid_table_schulte)       # создаём раскладку таблицей (QGridLayout)
    def delete_buttons(self):                           # удаление кнопок с таблицы
        if self.m_grid_table_schulte is not None:
            while self.m_grid_table_schulte.count():
                item = self.m_grid_table_schulte.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
    def set_table_size_3(self):
        self.table_size = 3  # размерность таблицы
        self.regenOstGridTable()  # обновляем таблицу
    def set_table_size_4(self):
        self.table_size = 4  # размерность таблицы
        self.regenOstGridTable()  # обновляем таблицу
    def set_table_size_5(self):
        self.table_size = 5  # размерность таблицы
        self.regenOstGridTable()  # обновляем таблицу
if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec_())

Если делаю так:

 size_button.triggered.connect(self.m_gridTable_Schulte.set_table_size(3))
...
    def set_table_size(self, count):
        self.table_size = count  # размерность таблицы
        self.regenOstGridTable()  # обновляем таблицу

То выдаёт ошибку:
size_button.triggered.connect(self.m_gridTable_Schulte.set_table_size(3))
TypeError: argument 1 has unexpected type ‘NoneType’

Отредактировано Doctor_Che (Янв. 4, 2017 02:59:00)

Офлайн

  • Пожаловаться

#2 Янв. 4, 2017 03:25:54

PyQt5. Передача данных в сигнале

Пример слота с параметром.

#!/usr/bin/env python3

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

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

self.initUI()

def initUI(self):

self.spin = QtGui.QSpinBox(self)
self.label = QtGui.QLabel(self)
self.label.move(30, 30)
self.label.resize(100, 20)

self.spin.valueChanged[int].connect(self.slot)

self.setGeometry(500, 500, 200, 100)
self.setWindowTitle('SpinBox + LineEdit')
self.show()

def slot(self, value):
self.label.setText(str(value * 2))

def main():

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

if __name__ == '__main__':
main()

Офлайн

  • Пожаловаться

#3 Янв. 4, 2017 14:24:16

PyQt5. Передача данных в сигнале

py.user.next
Пример слота с параметром.

За пример спасибо. С ним разобрался.
В нём передаётся значение самого спинбокса.
Но вот приладить вызов с параметром к элементу меню так и не получается…

Офлайн

  • Пожаловаться

#4 Янв. 4, 2017 14:59:23

PyQt5. Передача данных в сигнале

Это то же самое, только через лямбду.

#!/usr/bin/env python3

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

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

self.initUI()

def initUI(self):

self.spin = QtGui.QSpinBox(self)
self.label = QtGui.QLabel(self)
self.label.move(30, 30)
self.label.resize(100, 20)

self.spin.valueChanged.connect(lambda: self.slot(self.spin.value()))

self.setGeometry(500, 500, 200, 100)
self.setWindowTitle('SpinBox + LineEdit')
self.show()

def slot(self, value):
self.label.setText(str(value * 2))

def main():

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

if __name__ == '__main__':
main()

Офлайн

  • Пожаловаться

#5 Янв. 4, 2017 15:01:55

PyQt5. Передача данных в сигнале

     self.btn = QPushButton()
    self.count = 0
    self.btn.clicked,connect(self.on_click)
def on_click(self):
    print self.count

Отредактировано vic57 (Янв. 4, 2017 18:19:44)

Офлайн

  • Пожаловаться

#6 Янв. 4, 2017 18:13:22

PyQt5. Передача данных в сигнале

5-го нету QT есть 4-й , но не думаю что там сильно отличается.

 #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import random
from PyQt4.QtGui import QMainWindow, QApplication, QWidget, QGridLayout, QPushButton, QAction
from PyQt4.QtCore import QSize, pyqtSignal, QBasicTimer
class MainWindow(QMainWindow):
    setTablesSize = pyqtSignal(int) # наш сигнал и что он передает (целочисленное число)
    def __init__(self):
        super().__init__()        
        self.init_ui()
    def init_ui(self):
        
        self.m_gridTable_Schulte = OstGridTable(self)   # создание экземпляра класса OstGridTable
        # соединяем наш сигнал и метод set_table_size екземпляра self.m_gridTable_Schulte
        self.setTablesSize.connect(self.m_gridTable_Schulte.set_table_size)
        self.setCentralWidget(self.m_gridTable_Schulte)  # назначение таблицы (OstGridTable) центральным виджетом
        main_menu = self.menuBar()                      # создание экземпляра меню (строка меню)
        size_menu = main_menu.addMenu('Задать размер таблицы')
        size_button = QAction('3x3', self)
        size_button.setStatusTip('Создать поле размером 3x3')
        size_button.triggered.connect(lambda: self.setTablesSize.emit(3))
        size_menu.addAction(size_button)
        size_button = QAction('4x4', self)
        size_button.setStatusTip('Создать поле размером 4x4')
        size_button.triggered.connect(lambda: self.setTablesSize.emit(4))
        size_menu.addAction(size_button)
        size_button = QAction('5x5', self)
        size_button.setStatusTip('Создать поле размером 5x5')
        size_button.triggered.connect(lambda: self.setTablesSize.emit(5))
        size_menu.addAction(size_button)
        self.show()
                                          # отображаем окно на экране
class OstGridTable(QWidget):
    m_grid_table_schulte = QGridLayout()                # создаём экземпляр класса QGridLayout
    def __init__(self, parent):
        super().__init__(parent)
        self.table_size = 5                             # размерность таблицы
        self.regenOstGridTable()                        # обновляем таблицу
    def regenOstGridTable(self):                        # метод очищает таблицу
        self.delete_buttons()                           # запуск метода delete_buttons()
        names = [names + 1 for names in range(0, self.table_size * self.table_size)]
        random.shuffle(names)                       # перемешивание последовательности
        i = 0
        for j in range(0, self.table_size):
            for k in range(0, self.table_size):
                button = QPushButton(str(names[i]), self)  # создаём экземпляр класса QPushButton
                button.setMinimumSize(QSize(90, 90))  # задаём размер кнопки
                # привязываем сигнал к методу on_button_clicked (используем сигнал clicked)
                # button.clicked.connect(self.on_button_clicked)
                self.m_grid_table_schulte.addWidget(button, j, k)  # добавляем кнопки на раскладку
                i += 1
        self.setLayout(self.m_grid_table_schulte)       # создаём раскладку таблицей (QGridLayout)
    def delete_buttons(self):                           # удаление кнопок с таблицы
        if self.m_grid_table_schulte is not None:
            while self.m_grid_table_schulte.count():
                item = self.m_grid_table_schulte.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
    def set_table_size(self, count):
        self.table_size = count  # размерность таблицы
        self.regenOstGridTable()  # обновляем таблицу
if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec_())

Хотя в вашем случае вместо (lambda: self.setTablesSize.emit(3) можно было писать
lambda: self.m_gridTable_Schulte.set_table_size(3) но возможно вас инрересует именно как работает передача парметра в сигнале..

==============================
Помещайте код в теги:

Бериегите свое и чужое время.

Офлайн

  • Пожаловаться

#7 Янв. 4, 2017 23:47:32

PyQt5. Передача данных в сигнале

PEHDOM
5-го нету QT есть 4-й , но не думаю что там сильно отличается.

Спасибо огромное. Теперь разобрался.

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » PyQt5. Передача данных в сигнале

Возможно, вам также будет интересно:

  • Ошибка application load error 5 0000065434 как исправить
  • Ошибка api ms win eventing classicprovider
  • Ошибка args is error как исправить
  • Ошибка application load error 5 0000065434 гта
  • Ошибка api ms win crt string

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии