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 0
For bottom edge the y- co-ordinate should be always less than height of window – height of label
For left edge the x- co-ordinate should be always greater than 0
For right edge the x- co-ordinate should be always less than width of window – width of label
Implementation Steps :
1. Create a Main window
2. Create a label inside the main window
3. Add style sheet geometry to the label
4. Create a speed variable
5. Override the key press event
6. Inside the key press event get the current x and y co-ordinates of the label
7. 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
movemethod by incrementing/decrementing speed value from them
Below is the implementation
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.