Python Forum
help needed running a simple function in pyqt5 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: help needed running a simple function in pyqt5 (/thread-36225.html)

Pages: 1 2 3


help needed running a simple function in pyqt5 - diodes - Jan-30-2022

Hi

I am new to python and would like to get a small function to accept 2 variables and then execute a small function in a pyqt5 window. I have read two books and still can't do it. Here is the code I am trying to run. It is for a lotto quick picker using the Random library.

import random
print('Bills Lucky Quick Picker')
print('how many numbers')
x = int(input())
print('how many spots')
y = int(input())
for i in range(x):
    print(random.randint(1,y))
I would like a pyqt5 window to accept the two variables x and y and then run the for loop to print out the results within the window. I can get a window to run that function but it displays in the idle, not the GUI.

The program takes in input x and uses it to create the range of how many numbers the program picks and then the y variable (both integers) is the maximum number to select up to. so 6 and 49 would mean six numbers out of 49 total, a common lottery. If it's possible and easy adding in some code to not pick the same number twice would be nice as well. I have had success with this program online in casinos so I am really keen on making it run in its own GUI


RE: help needed running a simple function in pyqt5 - menator01 - Jan-30-2022

Here would be a good place to start.
Maybe here too.


RE: help needed running a simple function in pyqt5 - diodes - Jan-30-2022

I will follow the course and see what I can come up with, thanks for the help.


RE: help needed running a simple function in pyqt5 - diodes - Feb-15-2022

Ok, I did some reading and I made the UI. However, I am still clueless on how to get the button to take variables x and y from my input fields and then display them in a text edit box. here is the best I could come up with.

import random
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):     #my main window
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(358, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget) 
        self.pushButton.setGeometry(QtCore.QRect(120, 120, 89, 25))
        self.pushButton.setObjectName("pushButton")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(40, 50, 51, 25))
        self.lineEdit.setMaxLength(100)
        self.lineEdit.setObjectName("lineEdit")  # I need this to take my x integer
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(210, 50, 51, 25))
        self.lineEdit_2.setMaxLength(200)
        self.lineEdit_2.setObjectName("lineEdit_2")   # I need this to take my y integer
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(30, 20, 151, 17))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(210, 20, 131, 17))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(90, 160, 161, 17))
        self.label_3.setObjectName("label_3")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(70, 190, 201, 321))
        self.textEdit.setObjectName("textEdit")   #the place I want my results to display
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 358, 22))
        self.menubar.setObjectName("menubar")
        self.menuLotto_Picker = QtWidgets.QMenu(self.menubar)
        self.menuLotto_Picker.setObjectName("menuLotto_Picker")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.action_Exit = QtWidgets.QAction(MainWindow)
        self.action_Exit.setObjectName("action_Exit")
        self.actiongenerate = QtWidgets.QAction(MainWindow)
        self.actiongenerate.setObjectName("actiongenerate")  #with this action i want to generate the random numbers by pressing this button.
        self.menuLotto_Picker.addAction(self.action_Exit)
        self.menubar.addAction(self.menuLotto_Picker.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):  #the titles of all my labels
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Generate"))
        self.label.setText(_translate("MainWindow", "How Many Numbers"))
        self.label_2.setText(_translate("MainWindow", "How Many Spots"))
        self.label_3.setText(_translate("MainWindow", "Your random Numbers"))
        self.menuLotto_Picker.setTitle(_translate("MainWindow", "Lotto Picker"))
        self.action_Exit.setText(_translate("MainWindow", "&Exit"))
        self.actiongenerate.setText(_translate("MainWindow", "generate"))


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_())
if anyone can help me accomplish my goals I would be very thankful.


RE: help needed running a simple function in pyqt5 - menator01 - Feb-15-2022

Here is an example of what you want I think. I did not do any kind of validation on what is being entered. text will probably crash it.

import random as rnd
import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication, QWidget, QPushButton, QGridLayout, QLabel,
QLineEdit, QListWidget)


class Window(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Container
        container = QGridLayout()

        label = QLabel('How many spots')

        entry = QLineEdit()
        entry.setPlaceholderText('Enter a number here')
        entry.setStyleSheet('border: 1px solid black;')

        button = QPushButton('Submit')
        button.clicked.connect(lambda: self.picker(entry))

        self.listbox = QListWidget()

        container.addWidget(label, 0, 0, 1, 1)
        container.addWidget(entry, 0, 1, 1, 1)
        container.addWidget(button, 1, 0, 1, 2)
        container.addWidget(self.listbox, 2, 0, 1, 2)

        widget = QWidget()
        widget.setLayout(container)
        self.setCentralWidget(widget)

    def picker(self, spots):
        spots = int(spots.text())
        picks = []
        while len(picks) < spots:
            pick = rnd.randint(1, 49)
            if pick not in picks:
                picks.append(f'{pick}')
        nums = ', '.join(picks)
        self.listbox.addItem(nums)


def main():
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

main()



RE: help needed running a simple function in pyqt5 - diodes - Feb-15-2022

(Feb-15-2022, 09:21 AM)menator01 Wrote: Here is an example of what you want I think. I did not do any kind of validation on what is being entered. text will probably crash it.

import random as rnd
import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication, QWidget, QPushButton, QGridLayout, QLabel,
QLineEdit, QListWidget)


class Window(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Container
        container = QGridLayout()

        label = QLabel('How many spots')

        entry = QLineEdit()
        entry.setPlaceholderText('Enter a number here')
        entry.setStyleSheet('border: 1px solid black;')

        button = QPushButton('Submit')
        button.clicked.connect(lambda: self.picker(entry))

        self.listbox = QListWidget()

        container.addWidget(label, 0, 0, 1, 1)
        container.addWidget(entry, 0, 1, 1, 1)
        container.addWidget(button, 1, 0, 1, 2)
        container.addWidget(self.listbox, 2, 0, 1, 2)

        widget = QWidget()
        widget.setLayout(container)
        self.setCentralWidget(widget)

    def picker(self, spots):
        spots = int(spots.text())
        picks = []
        while len(picks) < spots:
            pick = rnd.randint(1, 49)
            if pick not in picks:
                picks.append(f'{pick}')
        nums = ', '.join(picks)
        self.listbox.addItem(nums)


def main():
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

main()

that is almost perfect, I needed the program to take a second argument of how many numbers to choose from. So how many numbers? and how many spots so that the program can be used for any lottery or keno. I will try to do it myself your help was great thank you.


RE: help needed running a simple function in pyqt5 - diodes - Feb-15-2022

ok that works great, I updated it a bit and almost got it perfect.

import random as rnd
import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication, QWidget, QPushButton, QGridLayout, QLabel,
QLineEdit, QListWidget)
 
 
class Window(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
 
        # Container
        container = QGridLayout()
 
        label = QLabel('How many Numbers')
        label2 = QLabel('How many Spots')
        
        entry = QLineEdit()
        entry.setPlaceholderText('picks')
        entry.setStyleSheet('border: 1px solid black;')

        entry2 = QLineEdit()
        entry2.setPlaceholderText('picks')
        entry2.setStyleSheet('border: 1px solid black;')

        button = QPushButton('Generate')
        button.clicked.connect(lambda: self.picker(entry))
 
        self.listbox = QListWidget()
 
        container.addWidget(label, 0, 0, 1, 1)
        container.addWidget(entry, 0, 1, 1, 1)
        container.addWidget(button, 2, 0, 1, 2)
        container.addWidget(label2, 1, 0, 1, 1)
        container.addWidget(entry2, 1, 1, 1, 1)
        container.addWidget(self.listbox, 3, 0, 1, 2)
 
        widget = QWidget()
        widget.setLayout(container)
        self.setCentralWidget(widget)
 
    def picker(self, spots):
        spots = int(spots.text())
        picks = []
        while len(picks) < spots:
            pick = rnd.randint(1, 49)
            if pick not in picks:
                picks.append(f'{pick}')
        nums = ', '.join(picks)
        self.listbox.addItem(nums)
 
 
def main():
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
 
main()
now I am working on replacing the 49 in the for while loop with a second variable. if you could do this easily it would be appreciated. The program is almost complete and functioning the way I would like you did a great job helping just need it to pick a variable amount of numbers from a variable amount of numbers. so example 10 from 80 or 4 from 80 and of course 6 from 49, the common lotteries I will be using it for. thanks again for all the help. I only have Arduino programming experience so python is exciting.


RE: help needed running a simple function in pyqt5 - menator01 - Feb-15-2022

If spots is less than numbers, you will get duplicates or it may go into an infinity loop.
import random as rnd
import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication, QWidget, QPushButton, QGridLayout, QLabel,
QLineEdit, QListWidget, QMessageBox)


class Window(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Container
        container = QGridLayout()

        label = QLabel('How many numbers?')
        label2 = QLabel('How many spots?')

        self.entry = QLineEdit()
        self.entry.setPlaceholderText('How many numbers?')
        self.entry.setStyleSheet('border: 1px solid black;')

        self.entry2 = QLineEdit()
        self.entry2.setPlaceholderText('How many spots?')
        self.entry2.setStyleSheet('border: 1px solid black;')

        button = QPushButton('Submit')
        button.clicked.connect(lambda: self.picker(self.entry, self.entry2))
        button2 = QPushButton('Clear')
        button2.clicked.connect(self.clear)

        self.listbox = QListWidget()

        container.addWidget(label, 0, 0, 1, 1)
        container.addWidget(self.entry, 0, 1, 1, 1)
        container.addWidget(label2, 1, 0, 1, 1)
        container.addWidget(self.entry2, 1, 1, 1, 1)
        container.addWidget(button, 2, 0, 1, 1)
        container.addWidget(button2, 2, 1, 1, 1)
        container.addWidget(self.listbox, 3, 0, 1, 2)

        widget = QWidget()
        widget.setLayout(container)
        self.setCentralWidget(widget)

    def clear(self):
        self.listbox.clear()

    def picker(self, how_many, spots):
        messages = ['Spot\'s can not be less than number', 'Only numbers can be entered']
        error = 0
        try:
            spots = int(spots.text())
            how_many = int(how_many.text())
            if spots < how_many:
                text = messages[0]
                error += 1
        except ValueError:
            error += 1
            text = messages[1]

        if error > 0:
            msg = QMessageBox()
            msg.setText(text)
            msg.setIcon(QMessageBox.Warning)
            msg.setWindowTitle('Warning Error!')
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
        else:
            picks = []
            while len(picks) < how_many:
                pick = rnd.randint(1, spots)
                if str(pick) not in picks:
                    picks.append(f'{pick}')
            nums = ', '.join(picks)
            self.listbox.addItem(nums)
        self.entry.clear()
        self.entry2.clear()


def main():
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

main()



RE: help needed running a simple function in pyqt5 - diodes - Feb-15-2022

That works perfectly. Exactly what I was trying to accomplish. I definitely learned a bunch. If I win the lotto with this I will look you up for a tip :)


RE: help needed running a simple function in pyqt5 - diodes - Feb-16-2022

Now that I have a variable numbers and spots quick picker, I have been trying to get it into a variable number of spots but with numbers only from the range of 0 to 9. for lotto's like the pick 2, pick 3, and pick 4 . Got it working but I can't get a clear function box working.

import random as rnd
import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication, QWidget, QPushButton, QGridLayout, QLabel,
QLineEdit, QListWidget)
 
 
class Window(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
 
        # Container
        container = QGridLayout()
 
        label = QLabel('How many spots')
 
        entry = QLineEdit()
        entry.setPlaceholderText('Enter a number here')
        entry.setStyleSheet('border: 1px solid black;')
 
        button = QPushButton('Submit')
        button.clicked.connect(lambda: self.picker(entry))
        button2 = QPushButton('Clear')
        button2.clicked.connect(self.clear)
 
        self.listbox = QListWidget()
 
        container.addWidget(label, 0, 0, 1, 1)
        container.addWidget(entry, 0, 1, 1, 1)
        container.addWidget(button, 1, 0, 1, 1)
        container.addWidget(button2, 1, 1, 1, 2)
        container.addWidget(self.listbox, 2, 0, 1, 2)
 
        widget = QWidget()
        widget.setLayout(container)
        self.setCentralWidget(widget)

    def clear(self):
        self.listbox.clear()
        self.entry.clear()
 
    def picker(self, spots):
        spots = int(spots.text())
        picks = []
        while len(picks) < spots:
            pick = rnd.randint(0,9)
            if pick not in picks:
                picks.append(f'{pick}')
        nums = ', '.join(picks)
        self.listbox.addItem(nums)
 
 
def main():
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
 
main()
help would be appreciated. I almost have it working but my clear button won't appear. Also since this is a single-digit picker repeats are fine. I got the button there but I cant get it to clear the user selected pick. I get this error
Traceback (most recent call last):
  File "/home/bill/Desktop/singledigitpicker.py", line 39, in clear
    self.entry.clear()
AttributeError: 'Window' object has no attribute 'entry'