简体   繁体   中英

How to change global values between classes in python

I need to send self.deviceIp=QLineEdit() last value to another class from class PopUpWindows So I am trying to use global variables:

I have an interface of the Tab Widget and before the TabWidget I have Pop up Window with PyQt5. When I start the interface, popUp windows openning and I give a number in QlineEdit for example I entered number of 12 and I equal to GLOBAL_VAL =12. So When I click the start button, TabWidget Interface is opening. Than when I am in the Tab1() I need to see GLOBAL_VAL =12 but I see 0 why this happenning, althogh I am using global words

GLOBAL_VAL=0

class PopUpWindows(QDialog):
    def __init__(self):
        super().__init__()
        self.setFixedSize(750, 450) #set window size
        self.msg = QVBoxLayout()
        self.deviceIpLabel = QLabel("Please Give number :")
        self.deviceIp=QLineEdit()
        self.layoutx = QGridLayout()
        self.buttoninterface = QPushButton('Start Interface', self)
        self.buttoninterface.clicked.connect(self.showinterface)
        self.layoutx.addWidget(self.deviceIpLabel,0,0)
        self.layoutx.addWidget(self.deviceIp,0,1)
        self.layoutx.addWidget( self.buttoninterface,1,0)

        self.setLayout(self.layoutx)
        self.setLayout(self.msg)

    def showinterface(self):
        # app = QApplication(sys.argv)
        # self.master.set_timeout(2.0)
        self.tabwidget = TabWidget()
        global GLOBAL_VAL
        GLOBAL_VAL = self.deviceIp.text()
        # print(HOST_ADDRESS)
        self.tabwidget.show()
        self.close()

class TabWidget(QDialog):
      tabwidget = QTabWidget(QWidget)
            tabwidget.addTab(Tab1(), "Tab1")

            tabwidget.addTab(Tab2(), "Tab2")
            ...


class Tab1(QWidget):


    ..

class Tab2()
          global GLOBAL_VAL
          print(GLOBAL_VAL) ... I want to see  12 but I see 0 in here
    ..

I think you probably don't call that function. If I do this

gv = 0
print("gv before change:", gv)
class class1(object):
    def __init__(self):
        self.some_variables = 1
        self.change_global_var()
    def change_global_var(self):
        global gv
        gv = 4
        print("gv in change_global_var:", gv)
class class2(object):
    def __init__(self):
        global gv
        print("gv in class2:", gv)
c = class1()
c2 = class2()

The result is this:

gv before change: 0
gv in change_global_var: 4
gv in class2: 4

You create the tabs "self.tabwidget = TabWidget()" before changing the variables through global "global GLOBAL_VAL, GLOBAL_VAL = self.deviceIp.text()"

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