so im trying to make a program that will tell the user his mouse position when he clicks anywhere on the screen but im getting the error: TypeError: Ui_MainWindow.on_click() missing 1 required positional argument: 'pressed' i dont understand why this is happening and ive tried switching the position of the "self" variable in the on_click function but it didnt fix it and i need the self parameter
from PyQt5 import QtCore, QtGui, QtWidgets
from PIL import ImageGrab
from pynput import mouse
import pyautogui
import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(306, 145)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label_x = QtWidgets.QLabel(self.centralwidget)
self.label_x.setGeometry(QtCore.QRect(70, 90, 71, 41))
self.label_x.setScaledContents(False)
self.label_x.setAlignment(QtCore.Qt.AlignCenter)
self.label_x.setWordWrap(False)
self.label_x.setObjectName("label_x")
self.label_y = QtWidgets.QLabel(self.centralwidget)
self.label_y.setGeometry(QtCore.QRect(160, 90, 71, 41))
self.label_y.setScaledContents(False)
self.label_y.setAlignment(QtCore.Qt.AlignCenter)
self.label_y.setWordWrap(False)
self.label_y.setObjectName("label_y")
self.button = QtWidgets.QPushButton(self.centralwidget)
self.button.setGeometry(QtCore.QRect(90, 20, 111, 61))
self.button.setObjectName("button")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.button.clicked.connect(self.onPosButtonClick)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Bot"))
self.label_x.setText(_translate("MainWindow", "0"))
self.label_y.setText(_translate("MainWindow", "0"))
self.button.setText(_translate("MainWindow", "Pick Location"))
def on_click(self, x, y, button, pressed):
if pressed:
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
#self.label_x.setText(QtCore.QCoreApplication.translate("MainWindow", str(x)))
#self.label_y.setText(QtCore.QCoreApplication.translate("MainWindow", str(y)))
mouse.Listener.stop()
listener = mouse.Listener(on_click=on_click)
def onPosButtonClick(self):
self.listener.start()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
new to python btw
CodePudding user response:
Because your listener (on_click
) is a class member, you must provide an object when you set the callback. That means listener
cannot be a class variable, as you have it now. Instead, you should do this in your setupUi
function:
self.listener = mouse.Listener(on_click=self.on_click)
However, you shouldn't needs to use pynput
for this at all. Qt can do this kind of mouse capture.