PyQt5 – Move the Label Position within the window using Arrow Keys

12 Jun, 2020
In this article we will see how we can move the label within the window using arrow keys i.e when ever the arrow key(direction key) get pressed it moves towards that direction. For example when user press the Up arrow key the label will move upward similarly for other arrow keys label will change its position as well.
Concept : We can change the position of the label by incrementing/decrementing the co-ordinate values of the label but do not increment or decrement if it reaches the any end of the side below is the data given to do when each arrow key is pressed.
When Up arrow key is pressed : X Co-ordinate remain same, decrement the Y Co-ordinate 
When Down arrow key is pressed : X Co-ordinate remain same, increment the Y Co-ordinate 
When Left arrow key is pressed : Decrement X Co-ordinate, Y Co-ordinate remain same
When Right arrow key is pressed : Increment X Co-ordinate, Y Co-ordinate remain same

Below is the edges restriction data so that label should remain in the window
For top edge the y- co-ordinate should be always greater than 0For bottom edge the y- co-ordinate should be always less than height of window – height of labelFor left edge the x- co-ordinate should be always greater than 0For right edge the x- co-ordinate should be always less than width of window – width of label
Implementation Steps :1. Create a Main window2. Create a label inside the main window3. Add style sheet geometry to the label4. Create a speed variable5. Override the key press event6. Inside the key press event get the current x and y co-ordinates of the label7. And check which key key is pressed and check if side end is not reached then update the x and y co-ordinates with the help of move method by incrementing/decrementing speed value from them
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # width of window        self.w_width = 500          # height of window        self.w_height = 500          # setting geometry        self.setGeometry(100, 100, self.w_width, self.w_height)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # speed variable        self.speed = 15      # method for components    def UiComponents(self):          # creating a label        self.label = QLabel(self)          # label width        self.l_width = 40          # label height        self.l_height = 40          # setting geometry to the label        self.label.setGeometry(200, 200, self.l_width, self.l_height)          # setting stylesheet to the label        self.label.setStyleSheet("QLabel"                                 "{"                                 "border : 4px solid darkgreen;"                                 "background : lightgreen;"                                 "}")          # override the key press event    def keyPressEvent(self, event):          # get the current co-ordinates of the label        # X Co-ordinate        x = self.label.x()          # Y Co-ordinate        y = self.label.y()          # if up arrow key is pressed        if event.key() == Qt.Key_Up:              # if top position is attained            if y > 0:                self.label.move(x, y - self.speed)          # if down arrow key is pressed        elif event.key() == Qt.Key_Down:              # if bottom position is attained            # for bottom point, bottom co-ordinate will be            # height of window - height of label            if y < self.w_height - self.l_height:                self.label.move(x, y + self.speed)          # if left arrow key is pressed        elif event.key() == Qt.Key_Left:              # if left end position is attained            if x > 0:                self.label.move(x - self.speed, y)          # if down arrow key is pressed        elif event.key() == Qt.Key_Right:              # if right end position is attained            # for right end point, right co-ordinate will be            # width of window - width of label            if x < self.w_width - self.l_width:                self.label.move(x + self.speed, y)          # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
PyQt-exercise
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function