Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
global variables
#1
I've read a view posts and articles about global variables so I don't understand why it doesn't work in my app.
In the code below pos1, pos2 and pos2 create an error at keyPressEvent: "local variable 'pos...' referenced before assignment".
Why? And how can I do it right?
pos is an index that I want to increase/decrease at keypress.

import sys

global pos1

class MainWindow(QtWidgets.QMainWindow):

    global pos2
    pos2 = 1
    pos1 = 1
    
    def __init__(self):
        super().__init__()

        global pos3
        pos3 = 1

        # main window
        self.setWindowTitle("Uhren II")
        self.setFixedSize(500, 500)
        self.setWindowIcon(QIcon("Uhren2.ico"))

        # ...

    def keyPressEvent(self, event):
        if type(event) == QtGui.QKeyEvent and (event.key() == QtCore.Qt.Key_Left or event.key() == QtCore.Qt.Key_Down) :
            pos1 -= 1
            pos2 -= 1
            pos3 -= 1
        if type(event) == QtGui.QKeyEvent and (event.key() == QtCore.Qt.Key_Right or event.key() == QtCore.Qt.Key_Up) :
            pos1 += 1
            pos2 += 1
            pos3 += 1
        print(pos1, pos2, pos3)

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
Reply


Messages In This Thread
global variables - by HeinKurz - Jan-17-2023, 04:51 PM
RE: global variables - by menator01 - Jan-17-2023, 05:37 PM
RE: global variables - by deanhystad - Jan-17-2023, 05:47 PM
RE: global variables - by HeinKurz - Jan-17-2023, 06:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand global variables 357mag 5 1,171 May-12-2023, 04:16 PM
Last Post: deanhystad
  Global variables or local accessible caslor 4 1,064 Jan-27-2023, 05:32 PM
Last Post: caslor
  Clarity on global variables JonWayn 2 977 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 4,787 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 2,694 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 4,310 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  Question regarding local and global variables donmerch 12 5,187 Apr-12-2020, 03:58 PM
Last Post: TomToad
  local/global variables in functions abccba 6 3,469 Apr-08-2020, 06:01 PM
Last Post: jefsummers
  Where to put the global keyword when assigning variables outside a function? new_to_python 8 3,075 Feb-09-2020, 02:05 PM
Last Post: new_to_python
  Please help me understand how to use global variables joew 6 3,630 Jan-05-2020, 06:03 PM
Last Post: joew

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020