Feb-17-2022, 04:32 PM
(This post was last modified: Feb-17-2022, 05:50 PM by menator01.
Edit Reason: Tweaked code to show either red or black text in listbox
)
import random as rnd import sys from PyQt5.QtWidgets import (QMainWindow, QApplication, QWidget, QPushButton, QGridLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMessageBox) from PyQt5.QtCore import Qt 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) spinbtn = QPushButton('Spin') spinbtn.clicked.connect(lambda: self.odd_even()) 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) container.addWidget(spinbtn, 4, 0, 1, 2) widget = QWidget() widget.setLayout(container) self.setCentralWidget(widget) def odd_even(self): color = rnd.choice(('red', 'black')) item = QListWidgetItem(f"{rnd.choice(('odd', 'even'))} {color}") if color == 'red': item.setForeground(Qt.red) self.listbox.addItem(item) 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()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags