简体   繁体   中英

Update a QLabel , using a QPushButton in a QDialog

I am just started to use the PyQt5 and I am trying to update the information of a label, through a button that is inside a subclass (QDialog). When I push the button, the program stop and show the message:

"AttributeError: 'New_Player_Window' object has no attribute 'name_window_label'

The idea is that when the Button is pressed, the Qlabel that by default is "Anonimous" become the Name of the User.

The code is:

from PyQt5 import QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, 
QLineEdit, QLabel, QWidget, QPushButton, QMessageBox, QAction, QMenu, 
QDialog
import sys

class General_Window(QMainWindow):
  def __init__(self):
    super().__init__()
    self.initUI()
  def initUI(self):
    self.resize(500, 500)
    self.move(300, 100)
    self.setWindowTitle('Black Jack')
    #MENUBAR
    menubar = self.menuBar()
    fileMenu = menubar.addMenu('File')
    newAct = QAction('New Player', self)
    newAct.triggered.connect(General_Window.new_player)
    fileMenu.addAction(newAct)
    #LABEL
    self.name_window_label = QLabel('Anonimous', self)
    self.name_window_label.move(245, 15)
    self.show()

  def update_window(self, value):
    print(str(value))
    self.name_window_label.setText(str(value))

  def new_player(self):
    class New_Player_Window(QDialog, General_Window):
        def __init__(self):
            super().__init__()
            self.initUI()

        def create(self):
            try:
                int(self.money.text()) + 2
            except:
                QMessageBox.question(self, 'PyQt5 message', "You need to 
                insert a Number", QMessageBox.Ok , QMessageBox.Ok) 
            else:
                global value
                value = self.name.text()
                print(value)
                self.update_window(value)

        def initUI(self):                   
            self.setGeometry(300, 230, 250, 120)
            self.setWindowTitle('User Information')    
            #TEXTBOX1
            self.name = QLineEdit(self)
            self.name.move(110, 5)
            self.name.resize(110,20)
            #TEXTBOX2
            self.money = QLineEdit(self)
            self.money.move(110, 40)
            self.money.resize(110,20)
            #BUTTON1
            self.button = QPushButton('Create', self)
            self.button.move(5,80)
            self.button.clicked.connect(self.create)
            #BUTTON2
            self.button2 = QPushButton('Cancel', self)
            self.button2.move(120,80)
            #LABELNAME
            self.name_label = QLabel('SHORT NAME', self)
            self.name_label.move(20,10)
            #LABELNAME
            self.money_label = QLabel('MONEY AVAILABLE', self)
            self.money_label.move(10,45)

            self.show()
            self.exec_()


    if __name__=="__main__":
        New_Player_Window()

if __name__=="__main__":
 app = QApplication(sys.argv)
 ag = General_Window()  
 sys.exit(app.exec_())

Try it:

import sys
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, 
                             QLineEdit, QLabel, QWidget, QPushButton, 
                             QMessageBox, QAction, QMenu, QDialog, QSpinBox)

class General_Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(500, 500)
        self.move(300, 100)
        self.setWindowTitle('Black Jack')
        #MENUBAR
        menubar  = self.menuBar()
        fileMenu = menubar.addMenu('File')
        newAct   = QAction('New Player', self)
        newAct.triggered.connect(self.new_player)
        fileMenu.addAction(newAct)
        #LABEL
        self.name_window_label = QLabel('Anonimous', self)
        self.name_window_label.move(245, 15)

    def update_window(self, value):
        print(str(value))
        self.name_window_label.setText(str(value))

    def new_player(self):
        self.newPlayerWindow = New_Player_Window(self)


class New_Player_Window(QDialog): 
    def __init__(self, parent=None):
        super().__init__(parent)

        self.parent = parent  
        self.value  = 12

        self.initUI()

    def create(self):
        value = "{} - {}".format(self.name.text(), self.value)
        print(value)
        self.parent.update_window(value)
        self.close()    

    def initUI(self):                   
        self.setGeometry(300, 230, 250, 120)
        self.setWindowTitle('User Information')    
        #TEXTBOX1
        self.name = QLineEdit(self)
        self.name.move(110, 5)
        self.name.resize(110,20)
        #TEXTBOX2
        self.money = QSpinBox(self) #QLineEdit(self)
        self.money.setRange(1, 99)
        self.money.setValue(12)
        self.money.valueChanged.connect(self.moneyValueChanged)
        self.money.move(110, 40)
        self.money.resize(110,20)
        #BUTTON1
        self.button = QPushButton('Create', self)
        self.button.move(5,80)
        self.button.clicked.connect(self.create)
        #BUTTON2
        self.button2 = QPushButton('Cancel', self)
        self.button2.move(120,80)
        #LABELNAME
        self.name_label = QLabel('SHORT NAME', self)
        self.name_label.move(20,10)
        #LABELNAME
        self.money_label = QLabel('MONEY AVAILABLE', self)
        self.money_label.move(10,45)
        self.exec_()

    def moneyValueChanged(self, value): 
        self.value = value   


if __name__=="__main__":
    app = QApplication(sys.argv)
    ag = General_Window() 
    ag.show()
    sys.exit(app.exec_())

在此处输入图片说明

You have several errors:

  • As you point out, General_Window has the name_window_label attribute so it would be expected that New_Player_Window would have it too, but name_window_label is created in initUI but you have overwritten it in the New_Player_Window class so that does not exist that attribute but even if it had it, it would not be the name_window_label of the other window since it is another class that has another object, I recommend reading about OOP and especially about inheritance and composition.

  • Having an internal class of another class is considered a bad practice (with exceptions such as django) since you are creating the class at every moment spending resources unnecessarily.

  • This is not an error in itself but is a bad practice, do not use global variables since debugging a global variable is complicated since it has a difficult life cycle that can hide other types of problems.

  • Finally consider using the appropriate widgets for the user to enter the appropriate data type, for example use QSpinBox for integer values so you avoid unnecessary checking. I also add the recommendation to the use of layouts as I will show in my answer.

Going to the design of the solution, when you create a widget consider it as a black box that receives inputs and generates outputs, if the output is synchronous it uses a method where you can retrieve that information and if it is asynchronous it uses a signal, on the other QDialog side is a class specialized in requesting information so you should not update the information in New_Player_Window but in General_Window for it you must pass the information. QDialog uses exec_() to return if the user accepts or rejects the request but for this you must call accept or reject.

import sys
from PyQt5 import QtCore, QtGui, QtWidgets


class New_Player_Window(QtWidgets.QDialog):
    def __init__(self):
        super().__init__()
        self.initUI()

    def get_values(self):
        return self.name.text(), self.money.value()

    def initUI(self):
        self.setWindowTitle('User Information')   
        #TEXTBOX1
        self.name = QtWidgets.QLineEdit()
        #TEXTBOX2
        self.money = QtWidgets.QSpinBox(maximum=2147483647)
        #BUTTON1
        self.button = QtWidgets.QPushButton('Create')
        self.button.clicked.connect(self.accept)
        #BUTTON2
        self.button2 = QtWidgets.QPushButton('Cancel')
        self.button2.clicked.connect(self.reject)

        lay = QtWidgets.QVBoxLayout(self)
        flay = QtWidgets.QFormLayout()
        flay.addRow("SHORT NAME", self.name)
        flay.addRow("MONEY AVAILABLE", self.money)
        lay.addLayout(flay)
        hlay = QtWidgets.QHBoxLayout()
        hlay.addWidget(self.button)
        hlay.addWidget(self.button2)
        lay.addLayout(hlay)
        self.setFixedSize(self.sizeHint())


class General_Window(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Black Jack')
        #MENUBAR
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        newAct = QtWidgets.QAction('New Player', self)
        newAct.triggered.connect(self.new_player)
        fileMenu.addAction(newAct)
        #LABEL
        self.name_window_label = QtWidgets.QLabel('Anonimous', alignment=QtCore.Qt.AlignCenter)
        widget = QtWidgets.QWidget()
        self.setCentralWidget(widget)
        lay = QtWidgets.QVBoxLayout(widget)
        lay.addWidget(self.name_window_label, alignment=QtCore.Qt.AlignTop)

    def update_window(self, value):
        self.name_window_label.setText(value)

    def new_player(self):
        w = New_Player_Window()
        if w.exec_() == QtWidgets.QDialog.Accepted:
            name, value = w.get_values()
            print(name, value)
            self.update_window(name)


if __name__=="__main__":
     app = QtWidgets.QApplication(sys.argv)
     ag = General_Window()  
     ag.show()
     sys.exit(app.exec_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM