something about pygame:'Group' object has no attribute to 'rect' - python-3.x

It's my first time to ask questions.I'm making a game called "Alien Invasion" in python.When I want to click the "Play",it does't work.I keep on getting this error:
Traceback (most recent call last):
File "alien_invasion.py", line 30, in <module>
File "alien_invasion.py", line 24, in run_game
Flie "D:\python_work\alien_invasion\game_function.py", line 38, in check_events
Flie "D:\python_work\alien_invasion\game_function.py", line 41, in check_play_button
AttributeError:'Group' object has no attribute 'rect'
This is my code about game_function:
def check_events(ai_settings,stats,play_button,screen,ship,aliens,bullets):
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
check_keydown_events(event,ai_settings,screen,ship,bullets)
elif event.type==pygame.KEYUP:
check_keyup_events(event,ship)
elif event.type==pygame.MOUSEBUTTONDOWN:
mouse_x,mouse_y=pygame.mouse.get_pos()
check_play_button(ai_settings,screen,ship,aliens,bullets,stats,play_button,mouse_x,mouse_y)
def check_play_button(ai_settings,screen,stats,play_button,ship,aliens,bullets,mouse_x,mouse_y):
button_clicked=play_button.rect.collidepoint(mouse_x,mouse_y)
if button_clicked and not stats.game_active:
pygame.mouse.set_visible(False)
stats.reset_stats()
stats.game_active=True
aliens.empty()
bullets.empty()
create_fleet(ai_settings,screen,ship,aliens)
ship.center_ship()
I want to know why this is happening and how to correct it.Thanks for your help.

You are passing the arguments in the wrong order. They need to be in the same order as in the function definition:
check_play_button(ai_settings,screen,stats,play_button,ship,aliens,bullets,mouse_x,mouse_y)
The error occurs because you pass aliens, which is obviously a sprite group, as the fourth argument. Then in the check_play_button function this aliens group gets assigned to the local variable play_button and since it has no rect attribute, Python raises the AttributeError.

Related

how to make a greater than or lower than with tkinter StringVar

My code keeps giving this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "d:/Python Code stuff I did/print.py", line 209, in <lambda>
button = Button(root,text="Change Config", width=20, height=3, bg="#0f0f0f",fg="#ffffff", command=lambda:[do_it(), do_it1(), do_it2(), do_it3(),do_the_it(),do_the_it1()])
File "d:/Python Code stuff I did/print.py", line 149, in do_the_it
if str(number_1) > 4:
TypeError: '>' not supported between instances of 'str' and 'int'
I want it to check if that specific number is greater than 4 for example i input a number for example lets say its 7 I want it to print and that number is too high here is my code:
def do_the_it():
a = updater['Trading Settings']['minimum_offer'].value
updater.read('settings.ini')
updater['Trading Settings']['minimum_offer'].value = number_1.get()
updater.update_file()
updater.read('settings.ini')
updater['Trading Settings']['maximum_offer'].value = number_2.get()
updater.update_file()
if str(number_1) > 4:
print("Number can only exceed to 4")
updater.read('settings.ini')
updater['Trading Settings']['minimum_offer'].value = 4
updater.update_file()
You can't compare a string to a number. Use:
if float(number_1.get()) > 4:
You can also use int(), but if some joker enters a decimal point, this will prevent errors.

Passing a python function as an arg to a function in PyQt5

Sorry for the long post but wished to give as much as poss
There is a lot of code not shown here but I'm trying to clean up a huge function of buttons in a PyQt5 Gui
I have a GUI output and all is working well and I'm now making an attempt to remove the repeated code and so creating a function to create the buttons.
In a functioned name initUI I have around 20 buttons. As can be seen from the code, the old way was creating each one separately.
What I have done is to create a function that the parameters are sent to and this then creates them.
This does work apart from defRun arg sent to button.
This is passing a call to another function I've highlighted with >>>>arg<<<< this isn't really in the code
class iac2tf(QMainWindow):
def __init__(self):
super(iac2tf, self).__init__()
self.initUI()
self.setGeometry(0, 0, 1700, 1000)........
def button (self, buttonName, buttonText, >>>>defRun<<<<, buttonWidth, buttonHeight, buttonx, buttony):
self.buttonName = QtWidgets.QPushButton(buttonText,self)
>>>>self.buttonName.clicked.connect(lambda:self.defRun)<<<<
self.buttonName.resize(buttonWidth,buttonHeight)
self.buttonName.move(buttonx,buttony)
self.buttonName.show()
def initUI(self):
#passed style
self.openFilebutton = self.button('openFile', 'Open File', >>>'open()'<<<< ,110,30,5,50)
#Old style
self.ProcessFile = QtWidgets.QPushButton('Process File',self)
self.ProcessFile.clicked.connect(self.processFile)
self.ProcessFile.resize(110,30)
self.ProcessFile.move(5, 80)
/......
....../
def open(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
file, _ = QFileDialog.getOpenFileNames(self, 'Ope.......
app = QApplication(sys.argv)
win = iac2tf()
win.show()
I've tried passing Knowing some would fail but wanted to cover all bases and was exasperated
str(open)
GUI opens with
<built-in function open>
On clicking button
File "/home/bob/present/proj/WorksArea/gui.py", line 38, in <lambda>
self.buttonName.clicked.connect(lambda:self.defRun)
AttributeError: 'iac2tf' object has no attribute 'defRun'
str(open())
self.openFilebutton = self.button('openFile', 'Open File', str(open()) ,110,30,5,50)
TypeError: Required argument 'file' (pos 1) not found
str(self.open)
GUI opens with
<bound method iac2tf.open of <__main__.iac2tf object at 0x7f87e73da948>>
On clicking button
Traceback (most recent call last):
File "/home/bob/present/proj/WorksArea/gui.py", line 38, in <lambda>
self.buttonName.clicked.connect(lambda:self.defRun)
AttributeError: 'iac2tf' object has no attribute 'defRun'
str(self.open())
Open file selection menu ie starts open func
self.open
GUI starts
<bound method iac2tf.open of <__main__.iac2tf object at 0x7fdcb2dee948>>
On clicking button
Traceback (most recent call last):
File "/home/bob/present/proj/WorksArea/gui.py", line 38, in <lambda>
self.buttonName.clicked.connect(lambda:self.defRun)
AttributeError: 'iac2tf' object has no attribute 'defRun'
'self.open'
'self.open()'
'open()'
'open'
opens GUI without error
on clicking button
Traceback (most recent call last):
File "/home/bob/present/proj/WorksArea/gui.py", line 38, in <lambda>
self.buttonName.clicked.connect(lambda:self.defRun)
AttributeError: 'iac2tf' object has no attribute 'defRun'
open
opens GUI with
<built-in function open>
on clicking button
Traceback (most recent call last):
File "/home/bob/present/proj/WorksArea/gui.py", line 38, in <lambda>
self.buttonName.clicked.connect(lambda:self.defRun)
AttributeError: 'iac2tf' object has no attribute 'defRun'
open()
self.openFilebutton = self.button('openFile', 'Open File', open() ,110,30,5,50)
TypeError: Required argument 'file' (pos 1) not found
passing to a local to func var all of above but is as is :(
Here is an example of passing functions as arguments.
class Template(QWidget):
def __init__(self):
super().__init__()
self.vbox = QVBoxLayout(self)
self.create_button('Open', self.open)
self.create_button('Close', self.close)
def create_button(self, text, slot):
btn = QPushButton(text)
btn.clicked.connect(slot)
self.vbox.addWidget(btn)
def open(self):
QFileDialog.getOpenFileName(self)
Also worth noting that the arg buttonName is never actually used in this function:
def button (self, buttonName, buttonText, >>>>defRun<<<<, buttonWidth, buttonHeight, buttonx, buttony):
self.buttonName = QtWidgets.QPushButton(buttonText,self)
. . .
That variable only exists in the local scope of the function, and self.buttonName refers to another object entirely. That is to say, if you wanted to refer to a button you created where you passed 'openFile' for the buttonName arg, it would not be called self.openFile, it would be called literally self.buttonName. You could however, use exec() to achieve this, although it is generally discouraged.

What does "TypeError: 'NoneType' object is not subscriptable" mean?

I am writing a snake game using Pygame in Python3. However, I keep getting this TypeError, not only do I have no idea what it means I have no idea how to fix it
I haven't really attempted anything as I have no idea what it is or how to fix it. This is the code:
def draw(self, surface, eyes=False):
dis = self.w // self.rows
i = self.pos[0]
j = self.pos[1]
The error message I keep getting is:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "snake.py", line 179, in <module>
main()
File "snake.py", line 175, in main
redrawWindow(win)
File "snake.py", line 127, in redrawWindow
snack.draw(surface)
File "snake.py", line 25, in draw
i = self.pos[0]
TypeError: 'NoneType' object is not subscriptable
This occurs when you try to index through a Nonetype object, e.g.,
>>> x = None
>>> x[0]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x[0]
TypeError: 'NoneType' object is not subscriptable
To properly solve your problem, please post the full code or where you set the initial value of self.pos. It seems that you're setting this variable to None.
This appears to be an excerpt from the python tutorial by Tech With Tim: https://techwithtim.net/tutorials/game-development-with-python/snake-pygame/tutorial-1/
It is actually caused by a misplaced return inside of the randomSnack while loop.
Full code here: https://pastebin.com/embed_js/jB6k06hG
If the return is inside the while loop (at line 162 in the pastebin) you get this error. I was following the same tutorial and got this error too.
# When you call (line 145)
snack.draw(surface)
# you are referencing the snack that was created with (line 193)
snack = cube(randomSnack(rows, s), color=(0,255,0))
# The randomSnack function returns an x and y (line 162)
return (x,y)
# that gets passed into the cube object's "start" parameter (line 12)
def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):

Python cmd shell: handling undefined commands

I'm writing a shell that must be able to take an unlimited number of commands. I can't figure out from the docs (https://docs.python.org/3.6/library/cmd.html) which say:
Cmd.default(line) Method called on an input line when the command
prefix is not recognized. If this method is not overridden, it prints
an error message and returns.
I must be writing the default() method incorrectly?
I've tried this:
import cmd
class MyShell(cmd.Cmd):
def default():
print('you entered this unknown command: ')
if __name__ == '__main__':
MyShell().cmdloop()
but get this (when I enter 'hi' in the shell):
(Cmd) hi
Traceback (most recent call last):
File "/Users/david/anaconda/lib/python3.6/cmd.py", line 214, in onecmd
func = getattr(self, 'do_' + cmd)
AttributeError: 'MyShell' object has no attribute 'do_hi'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "bitmessage_shell.py", line 9, in <module>
MyShell().cmdloop()
File "/Users/david/anaconda/lib/python3.6/cmd.py", line 138, in cmdloop
stop = self.onecmd(line)
File "/Users/david/anaconda/lib/python3.6/cmd.py", line 216, in onecmd
return self.default(line)
TypeError: default() takes 0 positional arguments but 2 were given
def default():
print('you entered this unknown command: ')
that doesn't work in a class. You need at least the object argument (self), or make the method static/class using #staticmethod or #classmethod decorators (but not very convenient, you may need the object state at some point)
Moreover, the parent class seems to pass the line, so now you need 2 arguments:
def default(self,line):
print('you entered this unknown command: ',line)

Tkinter error messages - redrawing buttons

I write chess on Python3, use Tkinter. I have a problem with bot-mode. Player correctly play: click on buttons and figures move. After player's turn bot should play.
def main():
start_position()
root.mainloop()
while king_alive:
global bot_turn
if bot_turn:
cells = l.bot_move(log_field)
replace(cells[0], cells[1])
bot_turn = False
this is function replace() which change condition of cells on the field
def replace(first_cell, second_cell):
if second_cell.figure.type != 'nofig':
delete_fig(second_cell.figure)
first_cell.clicked = False
second_cell.clicked = False
second_cell.fig_name = first_cell.fig_name
second_cell.fig_owner = first_cell.fig_owner
second_cell.figure = second_cell.get_figure()
first_cell.figure = l.NoFigure(first_cell.x, first_cell.y, "")
first_cell.fig_name = ""
first_cell.fig_owner = ""
field[second_cell.x][second_cell.y].configure(fg=second_cell.fig_owner, text=second_cell.fig_name)
field[first_cell.x][first_cell.y].configure(text="")
demark_cells()
people can easily play and move figures, but bot can't do it, however he use the same functions of movement - replace() (input for method replace() are correct. I can't understand the traceback
Traceback (most recent call last):
File "C:/Users/Даша/Desktop/python/task chess/graphics.py", line 176, in <module>
main()
File "C:/Users/Даша/Desktop/python/task chess/graphics.py", line 171, in main
replace(cells[0], cells[1])
File "C:/Users/Даша/Desktop/python/task chess/graphics.py", line 138, in replace
field[second_cell.x][second_cell.y]['fg'] = second_cell.fig_owner
File "C:\Python34\lib\tkinter\__init__.py", line 1275, in __setitem__
self.configure({key: value})
File "C:\Python34\lib\tkinter\__init__.py", line 1268, in configure
return self._configure('configure', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 1259, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".36689776"
how to solve the problem?
P.S. log_field is matrix of every cell conditions
field is matrix of tkinter buttons
You have a problem in the line:
field[second_cell.x][second_cell.y]['fg'] = second_cell.fig_owner
Because you have destroyed, or assigned a different variable to a widget that is called in that line. I don't know exactly what your variables are, but it is probably field[second_cell.x][second_cell.y]['fg'] or second_cell.

Resources