Moving object when button clicked- PYQT - python

I’ve been trying to make an object move between three locations upon clicking a button. This is the code that I have now
def objectMove():
If window.button.pressed():
window.object1.setGeometry(200,120,91,91)
window.object1.setGeometry(1,120,91,91)
window.object1.setGeometry(90,120,91,91)
window.button.clicked.connect(objectMove)
My intention for this code was to have an object move to these three locations every time the button is clicked and the button can only be clicked 9 times before the screen times out. But I’m unsure how I could fix this

hold qrects of positions in dict under self_def_init_
self.val = 0
self.val_dict = {0:QRect(200,120,91,91),1:QRect(200,120,91,91),2:QRect(200,120,91,91)}
and update your method as below code
def objectMove():
windowObject.setGeometry(self.val_dict[self.val])
self.val += 1
if self.val == 3:
self.val = 0

Related

For loop assign a variable name for each loop iteration

This is a part of a code I've been working on, during the for loop it iterates through product_buttons in order to define which button is selected, and after a button is selected I wanted to show which button was selected and I have managed to do it as follows:
product_buttons = [36,38,40] #raspberry pi pins
in_progress = False
ended = True
product = None
def show_msg(wid,msg):
wid.config(text = msg)
pass
def button_loop():
global in_progress,ended
waiting = False
product = None
while True:
for i in range(len(product_buttons)):
button = IO.input(product_buttons[i])
if button:
print(i,in_progress,ended,product)
if not in_progress:
product = i
while not ended:
time.sleep(0.1)
in_progress = True
show_msg(root.lab_quality,'Button {}
pressed'.format(i))
The code works fine and whenever a button is pressed it changes Button {} pressed with Button 0 pressed, Button 1 pressed or Button 2 pressed.
Now what I was trying to do was to assign a variable name to each iteration in the for loop in order to achieve something like:
i = 0 make i = to a variable for example let's call it a
i = 1 make i = to b
i = 2 make i = to c
So that (still for example) when button 0 is pressed it shows Button a is pressed.
I have tried to store the values like this quality={1:a, 2:b, 3:c} and then call it with show_msg(root.lab_quality,'Button {} pressed'.format(quality)), this was the idea I had in mind but didn't work out and I am a bit stuck and I need to be pointed in the right direction so that I can eventually work it out.
Any help will be greatly appreciated!
You need to define quality as a dictionary like this: quality={'1':'a', '2':'b', '3':'c'}. Then, you can call show_msg function:
show_msg(root.lab_quality,'Button {} pressed'.format(quality[str(i)]))
This way you use the value of i variable as the key to read its name from the quality dictionary.
Thanks guys I have worked it out I did:
btn = ['a','b','c']
show_msg(root.lab_quality,'QUALITY {}'.format(btn[j]))
and works like a charm, was so easy I don't know why I didn't see it before.

Execute only once in python

So in my game I have a class called MovementService. This class handles moving an object when the uses presses an arrow key. However, when you press the up arrow 5 times in a row real quick, the object will move one square 5 times. This feels weird, because you're already done with pressing, but the character is still moving.
So I went and added some code to the class to try and prevent that. But now the movement is only executed once. But thing is, it's the first movement. How can I make sure it's the last press?
class MovementService():
lastExecutionEpoch = 0
minimumDifference = 1
def moveUp(self):
self.execute('MOVEUP')
def moveDown(self):
self.execute('MOVEDOWN')
def execute(self, movement):
if self.lastExecutionEpoch < (int(time.time()) - self.minimumDifference):
self.lastExecutionEpoch = int(time.time())
...
Do the actual movement
...

Updating object on Python < arcade library >

I'm currently coding in some assignment.
I create a class named Ship and created some methods to make the object class ship be able to move.
class Ship():
def __init__(self):
self.center.x = 400
self.center.y = 300
self.velocity.dx = .25
self.velocity.dy = .25
def advance_down(self):
self.center.y = self.center.y - self.velocity.dy
This is my code
def check_keys(self):
"""
This function checks for keys that are being held down.
You will need to put your own method calls in here.
"""
if arcade.key.DOWN in self.held_keys:
self.ship1.advance_down()
advance down just changes the position
def on_key_press(self, key: int, modifiers: int):
"""
Puts the current key in the set of keys that are being held.
You will need to add things here to handle firing the bullet.
"""
if key == arcade.key.DOWN:
self.held_keys.add(key)
This adds the current key being pressed to the set of self.held_keys.
I'm calling an update of the positon.
def update(self, delta_time):
"""
Update each object in the game.
:param delta_time: tells us how much time has actually elapsed
""
self.ship1.advance_down()
when I run the code I'm able to display everything just fine but it's not doing anything once I press my keys.
Any ideas why?

Passing variable from one function to another in same class?

I'm trying to create a button that changes colors on click.
After digging around in an old Python book I haven't looked at in years, I've gotten to the point where I make the the button, but I can't figure out how to pass i into the second function so it increments and is then is reset to 0.
I suppose I could just increment I on click in the first function, but now I'm annoyed and want to figure it out.
Instead of self.change_color I tried change_color(i). That threw an error. Same with trying self.change_color(i).
I'm not sure what to do at this point.
import tkinter
class joeGUI:
def __init__(self):
i = 0
colorArray = ['blue','DarkGreen','red','yellow']
self.main_window = tkinter.Tk()
self.color_button = tkinter.Button(self.main_window,
text = 'Click to Change Color',
command = self.change_color,
bg = colorArray[i])
self.color_button.pack()
tkinter.mainloop()
def change_color(self):
if (count < 3):
count += 1
else:
count = 0
return count;
joe_gui = joeGUI()
Store i as a class attribute (self.i = 0) and change the references of count to self.i.

Blocking button click signals in PyQt

I have a program that uses pyqt's .animateClick() feature to show the user a sequence of different button clicks that the user has to copy in that specific order. The problem is I don't want the animateClick() to send a signal, I only want the button click signals from the user. Here is some of my code to demonstrate what I mean, and how I tried to solve that problem (that doesn't work). I simplified my code quite a bit so its easier to read, let me know if you have any questions.
from PyQt4 import QtCore,QtGui
global flag
global ai_states
ai_states = []
user_states = []
class Program(object):
# Set up the push buttons
#Code Here.
# Connect push buttons to function get_state()
self.pushButton.clicked.connect(self.get_state)
self.pushButton_2.clicked.connect(self.get_state)
self.pushButton_3.clicked.connect(self.get_state)
self.pushButton_4.clicked.connect(self.get_state)
# Code that starts the start() function
def start(self):
flag = 0
ai_states[:] = []
i = -1
# Code here that generates ai_states, numbers 1-4, in any order, based on button numbers.
for k in ai_states:
i = i + 1
# Code here that animates button clicks determined by ai_states
# Changes the flag to 1 once the loop ends
if i == len(ai_states):
flag = 1
def get_state(self):
if flag == 1:
user_states.append(str(self.centralWidget.sender().text()))
else:
pass
if len(user_states) == len(ai_states):
# Checks to make sure the user inputted the same clicks as the ai_states
Even though the flag does come out to be 1 after the start() function, it is still appending the animatedClick() signals. What am I doing wrong? I'm new to GUI programming, so I'm probably going about this in a very bad way. Any help would be appreciated.
Never use global variables unless you really have to. If you need shared access to variables, use instance attributes:
from PyQt4 import QtCore,QtGui
class Program(object):
def __init__(self):
self.ai_states = []
self.user_states = []
self.flag = 1
# Set up the push buttons
# Code Here
# Connect push buttons to function get_state()
self.pushButton.clicked.connect(self.get_state)
self.pushButton_2.clicked.connect(self.get_state)
self.pushButton_3.clicked.connect(self.get_state)
self.pushButton_4.clicked.connect(self.get_state)
# Code that starts the start() function
def start(self):
self.flag = 0
del self.ai_states[:]
i = -1
# Code here that generates ai_states, numbers 1-4, in any order, based on button numbers.
for k in self.ai_states:
i = i + 1
# Code here that animates button clicks determined by ai_states
# Changes the flag to 1 once the loop ends
self.flag = 1
def get_state(self):
if self.flag == 1:
self.user_states.append(str(self.centralWidget.sender().text()))
if len(self.user_states) == len(self.ai_states):
# Checks to make sure the user inputted the same clicks as the ai_states

Categories