python AttributeError: _exit_ 这是什么错误

python AttributeError: exit 这是什么错误

2个回答

你可能要贴出完整的代码才行,猜测你出错的代码可能是在with语句块中。
下面是在stackoverflow撒花姑娘找到的一句话
with statement is for object that have __enter__ and __exit__ functions, i.e. Context Manager Types
希望对你有些启发

没有这个属性,或者定义有问题

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
python 使用with con:连接数据库时 报错AttributeError: __enter__怎么解决呢?

# python 使用with con:连接数据库代码如下 import MySQLdb as mdb import sys con=mdb.connect('localhost', 'root', 'mysql', 'test'); with con: cur = con.cursor() # 执行一个查询 cur.execute("SELECT VERSION()") # 取得上个查询的结果,是单个结果 data = cur.fetchone() print("Database version : %s " % data) 运行上面的 程序会报下面的错误: Traceback (most recent call last): File "C:/Users/x'x'x/PycharmProjects/test01/python_mysql/test_mysql.py", line 8, in <module> with con: AttributeError: __enter__ 怎么解决呢?

python3,windos7系统提示AttributeError: 'Feijidazhan' object has no attribute 'back_group'

1AttributeError: 'Feijidazhan' object has no attribute 'back_group' ```class Feijidazhan(object): def __init__(self): print("初始化游戏") #1创建游戏窗口 self.feiji_mode = pygame.display.set_mode(DA_XIAO.size) #2 创建游戏时钟 self.clock = pygame.time.Clock() #3私有方法精灵和精灵组的创建 def spirit_jiling(self): #1背景滚动 beijing = Bjinjing(".\\images\\background.png") self.back_group = pygame.sprite.Group(beijing) def start_game(self):#开始游戏 print("开始游戏") while True: # 1刷新帧率 self.clock.tick(ZHEN_LV) # 2事件监听 self.__jian_ting() # 3碰撞检测 self.__peng_zhuang() # 4更新绘制精灵,英雄 self.__hui_zhi() # 5更新显示 pygame.display.update() def __jian_ting(self): for event in pygame.event.get(): if event.type == pygame.QUIT: Feijidazhan.__game_over() def __peng_zhuang(self): pass def __hui_zhi(self): self.back_group.update() self.back_group.draw(self.feiji_mode) @staticmethod def __game_over(): print("游戏结束") pygame.quit() exit() if __name__ == '__main__': #创建对象 game_ = Feijidazhan() #启动游戏 ```

新人使用pycharm运行飞机大战项目报如下错误:AttributeError: module 'pygame.image' has no attribute 'get_rect'

看着网上的教学视频一步一步下来,当建立敌机的精灵后,在程序中调用这个精灵时就会报错,单独运行精灵程序时不会报错,在网上也找了相关的资料,但类似的好像也不对; 主程序代码如下: ``` import pygame from plane_sprites import * pygame.init() #创建游戏窗口 480*700 screen = pygame.display.set_mode((480,700)) #绘制背景图像 bg = pygame.image.load("./images/background.png") screen.blit(bg,(0,0)) #绘制英雄的飞机 hero = pygame.image.load("./images/me1.png") screen.blit(hero,(150,400)) #可以在所有绘制工作结束后,统一调度update方法啊 pygame.display.update() #创建时钟对象 clock = pygame.time.Clock() #1.定义rect记录飞机的初始位置 hero_rect = pygame.Rect(150,400,102,126) #创建敌机的精灵 enemy = GameSprite("./images/enemy1.png") enemy1 = GameSprite("./images/enemy1.png",2) #创建敌机的精灵组 enemy_group = pygame.sprite.Group(enemy,enemy1) #游戏循环>意味着游戏正式开始 while True: #1.可以指定循环体内部的代码执行的频率 clock.tick(60) """ #捕获事件 event_list = pygame.event.get() if len(event_list) > 0: print(event_list) """ #事件监听 for event in pygame.event.get(): #判断用户是否点击了关闭按钮 if event.type == pygame.QUIT: print('退出游戏!') pygame.quit() #直接退出系统 exit() #2.修改飞机的位置 hero_rect.y -= 1 #判读飞机的位置 if hero_rect.y <= -126: hero_rect.y = 700 #3.调用blit方法绘制图像 screen.blit(bg,(0,0)) screen.blit(hero,hero_rect) #让精灵族调用两个方法 #update - 让组中的所有精灵都更新位置 enemy_group.update() #draw - 在screen上显示所有的精灵 enemy_group.draw(screen) #4.使用update方法更新显示 pygame.display.update() pygame.quit() ``` 调用的精灵程序如下: ``` import pygame class GameSprite(pygame.sprite.Sprite): """飞机大战精灵""" def __init__(self, image_name, speed=1): #调用父类的初始化方法 super().__init__() #定义对象的属性 self.image = pygame.image.load(image_name) self.rect = pygame.image.get_rect() self.speed = speed def update(self): #在屏幕的垂直方向移动 self.rect.y += self.speed ``` 运行后报如下的错误: AttributeError: module 'pygame.image' has no attribute 'get_rect' ![图片说明](https://img-ask.csdn.net/upload/202002/08/1581141436_82065.png) 还请各位大佬有时间能帮忙看下这个问题我出错在哪里了,谢谢哈

笨方法学python3上的习题43AttributeError: 'NoneType' object has no attribute 'enter',哪错了

from sys import exit from random import randint from textwrap import dedent class Scene(object): def enter(self): print("This scene is not yet configured.") print("Subclass it and implement enter().") exit(1) class Engine(object): def __init__(self,scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene('finished') while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) # be sure to print out the last scene current_scene.enter() class Death(Scene): quips = [ "You died. You kinda suck at this.", "Your mom would be pround...if she were smarter.", "such a luser.", "I have a small puppy that's better st this.", "You're worse than your Dad's jokes.", ] def enter(self): print(Death.quips[randint(0, len(self.quips)-1)]) exit(1) class CentralCorridor(Scene): def enter(self): print(dedent(""" The Gothons of Planet Percal #25 have invaded your ship and destroyed your entire crew. You are the last surviving member and your last mission is to get the neutron destruct bomb from the Weapons Armory, put it in the bridge, and blow the ship up after getting into an escape pod. You're runing down the central corridor to the Weapons Armory when a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume flowing around his hate filled body. He's blocking the door to the Armory and zbout to pull a weapon to blast you. """)) action = input("> ") if action == "shoot!": print(dedent(""" Quick on the draw you yank out your blaster and fire it at the Gothon. His clown costume is flowing and moving around his body, which throws off your aim. Your laser hits his costume but misses him entirely. This completely ruins his brand new costume his mother bought him, which makes him fly into an insane rage and blast you repeattedly in the face until you are dead. Then he eats you. """)) return 'death' elif action == "dodge!": print(dedent(""" Lke a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out. You wake up shortly after only to die as the Gothon stomps on your head and eats you. """)) return 'death' elif action == "tell a joke": print(dedent(""" Lucky for you they made you learn Gothon insults in the academy. You tell the one Gothon joke you know: Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr. The Gothon stops, tries not to laugh, then busts out laughing and can't move. While he's laughing you run up and shoot him square in the head putting him down, then through the Weapon Armory door. """)) return 'laser_weapon_armory' else: print("DOES NOT COMPUTE!") return 'central_corridor' class LaserWeaponArmory(Scene): def enter(self): print(dedent(""" Youd do a dive roll into the Weapon Armory, crouch and scan the room for more Gothons that might be hiding. It's dead quiet, too quiet,You stand up and run to the far side off the room and find the neutron bomb in its container. There's a keypad lock on box and you need the code to get the bomb out. If you get the code wrong 10 times then the lock closes forever and you can't get the bomb. The code is 3 digits. """)) code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}" guess = input("[keypad]> ") guesses = 0 while guess != code and guesses<10: print("BZZZZEDDD!") guesses += 1 guess = input("[keypad]> ") if guess == code: print(dedent(""" The container clicks open and the seal breaks, letting gas out. You grab the neutron bomb and run as fast as you can to the bridge where you must place it in the right spot. """)) return 'the bridge' else: print(dedent(""" The lock buzzes one last time and then you hear a sickening melting sound as the mechanism is fused together. You decide to sit there, and finally the Gothons blow up the ship from their ship and you die. """)) return 'death' class TheBridge(Scene): def enter(self): print(dedent(""" You burst onto the Bridge eith the entron destruct bomb under your arm and surprise 5 Gonthons who are trying to take control of the ship. Each of them has an even uglier clown sostume than last.They have't pulled their weapons out yet, as they see the active bomb under your arm and don't want to set it off. """)) action = input("> ") if action == "throw the bomb": print(dedent(""" In a panic you throw the bomb at group of Gothons and make a leap for the door. Right as you drop it a Gothon shoots you right in the back killing you. As you die you see another Gothon frantically try to disarm the bomb. You die knowing they will probably blow up when it goes off. """)) return 'death' elif action == "slowly place the bomb": print(dedent("""" You point your blaster at the bomb under your arm and the Gothons put their hands up adn start to sweat. You inch backward to the door, open it, and then carefully place the bomb on the floor, pointing your blaster at it. You then jump back through the door punch the close button and blast the lock so the Gothons can't get out. Now that bomb is placed you run to the escape pod to get off this tin can. """)) return 'escape_pod' else: print("DOES NOT COMPUTE!") return 'the_bridge' class EscapePod(Scene): def EscapePod(self): print(dedent(""" You rush through the ship desperately trying to make it to the escape pod before the whole ship explodes. It seems like hardly any Gothons are on the ship, so you run is clear of interference. You get to the chamber with the escape pods, and now need to pick one to take. Some of them could be damaged but you don't have time to look. There;s 5pods, which one do you take? """)) good_pod = randint(1,5) guess = input("[pod #> ") if int(guess) != good_pod: print(dedent(""" You jump into pod {guess} and hit the eject button. The pod escapes out into the void of space, then implodes as the hull ruptures, crushing your body into jam jelly. """)) return 'death' else: print(dedent(""" You jump into pod {guess} and hit the eject button. The pod easily slides out into space heading to the plantes below. As it flies to the planet, you look back and see your ship implode then explode like a bright star, taking out the Gothon ship at the same time. You won! """)) return 'finished' class Finished(Scene): def enter(self): print("You won! Good job.") return 'finished' class Map(object): scenes = { 'central_corridor': CentralCorridor(), 'laser_weapon_armory':LaserWeaponArmory(), 'the_bridge':TheBridge(), 'escape_pod':EscapePod(), 'death':Death(), 'finished':Finished(), } def __init__(self, start_scene): self.start_scene = start_scene def next_scene(self, scene_name): val = Map.scenes.get(scene_name) return val def opening_scene(self,): return self.next_scene(self.start_scene) a_map = Map('central_corrider') a_game = Engine(a_map) a_game.play() 返回结果: Traceback (most recent call last): File "F:/Python/test43.py", line 228, in <module> a_game.play() File "F:/Python/test43.py", line 18, in play next_scene_name = current_scene.enter() AttributeError: 'NoneType' object has no attribute 'enter' Process finished with exit code 1 看了好久,就是找不到是哪里错了,很烦

AttributeError: module 'keras.backend' has no attribute 'set_image_dim_ordering'

运行后报错,出现以下问题,试过很多方法但就是不行,请问这怎么解决 ![图片说明](https://img-ask.csdn.net/upload/202003/06/1583479858_171879.png) ``` D:\ProgramFiles\Anaconda3\python.exe F:/课程/lpr-master/lpr.py Using TensorFlow backend. 2020-03-06 14:30:11.878437: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found 2020-03-06 14:30:11.916527: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. Traceback (most recent call last): File "F:/课程/lpr-master/lpr.py", line 12, in <module> from hyperlpr_py3 import pipline as pp File "F:\课程\lpr-master\hyperlpr_py3\pipline.py", line 5, in <module> from . import segmentation File "F:\课程\lpr-master\hyperlpr_py3\segmentation.py", line 22, in <module> K.set_image_dim_ordering('tf') AttributeError: module 'keras.backend' has no attribute 'set_image_dim_ordering' Process finished with exit code 1 ``` 看了这位大大的解决方法,我输入命令后(pip install h5py==2.8.0rc1),却疯狂报错 ![图片说明](https://img-ask.csdn.net/upload/202003/06/1583479156_634297.jpg) 错误如下 ``` D:\>pip install h5py==2.8.0rc1 Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple Collecting h5py==2.8.0rc1 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/34/07/4f8f6e4e478e9eabde25dea6b4478016e625b2dac6aaded78ba0316c86fe/h5py-2.8.0rc1.tar.gz (263 kB) Requirement already satisfied: numpy>=1.7 in d:\programfiles\anaconda3\lib\site-packages (from h5py==2.8.0rc1) (1.16.5) Requirement already satisfied: six in d:\programfiles\anaconda3\lib\site-packages (from h5py==2.8.0rc1) (1.12.0) Building wheels for collected packages: h5py Building wheel for h5py (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'd:\programfiles\anaconda3\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\93790\\AppData\\Local\\Temp\\pip-install-5rvq0cey\\h5py\\setup.py'"'"'; __file__='"'"'C:\\Users\\93790\\AppData\\Local\\Temp\\pip-install-5rvq0cey\\h5py\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\93790\AppData\Local\Temp\pip-wheel-f05vtg7o' cwd: C:\Users\93790\AppData\Local\Temp\pip-install-5rvq0cey\h5py\ Complete output (1294 lines):(1294行错误) .......... building 'h5py.defs' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- Rolling back uninstall of h5py Moving to d:\programfiles\anaconda3\lib\site-packages\h5py-2.9.0.dist-info\ from d:\programfiles\anaconda3\lib\site-packages\~5py-2.9.0.dist-info Moving to d:\programfiles\anaconda3\lib\site-packages\h5py\ from d:\programfiles\anaconda3\lib\site-packages\~5py ERROR: Command errored out with exit status 1: 'd:\programfiles\anaco nda3\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\93790\\AppData\\Local\\Temp\\pip-install-5rvq0cey\\h5py\\setup.py'"'"'; __file__='"'"'C:\\Users\\93790\\AppData\\Local\\Temp\\pip-install-5rvq0cey\\h5py\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\93790\AppData\Local\Temp\pip-record-zz3q07kh\install-record.txt' --single-version-externally-managed --compile --install-headers 'd:\programfiles\anaconda3\Include\h5py' Check the logs for full command output. ```

python显示 screen = pygame.display.set_mode((ai_setting.screen_width, ai_setting.screen_height)) AttributeError: 'Settings' object has no attribute 'screen_width'

#萌新向各位好心的大佬求教 import sys import pygame from settings import Settings def run_game(): #初始化pygame,设置和屏幕对象 pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #开始游戏的主循环 while True: #初始化pygame.设置和屏幕对象 # 监视键盘和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #每次循环时都重绘制屏幕 scree.fill(ai_settings.bg_color) #让最近的绘制的屏幕可见 pygame.display.flip() run_game() #按教程书编写的模块 class Settings(): """储存《外星人入侵》的所有设置的类""" def _init_(self,screen_width,screen_height,bg_color): """初始化游戏的设置""" #屏幕设置 self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230,230,230) #一运行就报错 screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) AttributeError: 'Settings' object has no attribute 'screen_width' #由衷的感谢大佬的帮助

python执行cursor = conn.cursor()报错

在执行cursor = conn.cursor()报错 ![图片说明](https://img-ask.csdn.net/upload/201704/26/1493196649_619205.png) Traceback (most recent call last): File "mid_tables.py", line 17, in <module> cursor= conn.cursor() File "/usr/lib/python2.6/site-packages/impala/hiveserver2.py", line 125, in cursor session = self.service.open_session(user, configuration) File "/usr/lib/python2.6/site-packages/impala/hiveserver2.py", line 995, in open_session resp = self._rpc('OpenSession', req) File "/usr/lib/python2.6/site-packages/impala/hiveserver2.py", line 923, in _rpc response = self._execute(func_name, request) File "/usr/lib/python2.6/site-packages/impala/hiveserver2.py", line 940, in _execute return func(request) File "/usr/lib/python2.6/site-packages/impala/_thrift_gen/TCLIService/TCLIService.py", line 175, in OpenSession return self.recv_OpenSession() File "/usr/lib/python2.6/site-packages/impala/_thrift_gen/TCLIService/TCLIService.py", line 193, in recv_OpenSession result.read(self._iprot) File "/usr/lib/python2.6/site-packages/impala/_thrift_gen/TCLIService/TCLIService.py", line 1109, in read fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) AttributeError: 'TBufferedTransport' object has no attribute 'trans'

运行python批处理文件,报了一个缺少属性“key”错误,找到源码但是看不懂,求大佬们解答

在使用自己的数据集做训练时,用到一个retrain.py的文件,之后通过批处理文件运行 以下是批处理文件代码: ``` python D:\python\Anaconda\envs\tensorflow\tensorflow-master\tensorflow\examples\image_retraining\retrain.py ^ --bottleneck_dir bottleneck ^ --how_many_training_steps 200 ^ --model_dir D:\python\Anaconda\envs\tensorflow\inception_model ^ --output_graph output_graph.pb ^ --output_labels output_labels.txt ^ --image_dir data/train/ pause ``` 调用时,报了 File "D:\python\Anaconda\envs\tensorflow\tensorflow-master\tensorflow\examples\image_retraining\retrain.py", line 1313, in <module> tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) File "D:\python\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run _sys.exit(main(argv)) File "D:\python\Anaconda\envs\tensorflow\tensorflow-master\tensorflow\examples\image_retraining\retrain.py", line 982, in main class_count = len(image_lists.keys()) AttributeError: 'NoneType' object has no attribute 'keys' 错误最后是说982行缺少keys属性,但不知如何修改 retrain代码太长,只能把链接发上来

[python报错问题]哪位老司机能带带我~~~~~

[最近在做GitHut上的Harvard-cs109,遇到一个地方疯狂报错,求老司机指指路(右边是链接)](https://github.com/cs109/content/blob/caffc21c8f7c758c1884852ed023d29dccea063f/HW1_solutions.ipynb "") 以下是报错的地方: ``` errors = all_error_data() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-18-aea6d425eefd> in <module>() ----> 1 errors = all_error_data() <ipython-input-17-2a9c686164e8> in all_error_data() 17 #your code here 18 def all_error_data(): ---> 19 data = [error_data(race_page) for race_page in find_governor_races(page)] 20 return pd.concat(data, ignore_index=True) <ipython-input-14-5c576ec1e316> in error_data(url) 48 #compute forecast length in days 49 #(assuming that last forecast happens on the day of the election, for simplicity) ---> 50 forecast_length = (df.date.max() - df.date).values 51 forecast_length = forecast_length / np.timedelta64(1, 'D') # convert to number of days 52 //anaconda/lib/python2.7/site-packages/pandas/core/generic.pyc in __getattr__(self, name) 2667 if name in self._info_axis: 2668 return self[name] -> 2669 return object.__getattribute__(self, name) 2670 2671 def __setattr__(self, name, value): AttributeError: 'DataFrame' object has no attribute 'date' ```

Python报错'xxx' object has no attribute 'xxx'

小白刚刚接触Python,想使用Python做一个用户注册和登陆的界面,使用pyqt从ui文件转换成py文件,但在转换完成之后执行报错,求大神解答。 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'sign.ui' # # Created: Sun Nov 13 17:09:05 2016 # by: PyQt4 UI code generator 4.11.3 # # WARNING! All changes made in this file will be lost! import sys from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(747, 564) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.label = QtGui.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(50, 30, 211, 61)) self.label.setStyleSheet(_fromUtf8("\n" "font: 75 22pt \"Microsoft YaHei UI\";")) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QtGui.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(50, 120, 81, 18)) self.label_2.setStyleSheet(_fromUtf8("font: 9pt \"Microsoft YaHei UI\";")) self.label_2.setObjectName(_fromUtf8("label_2")) self.lineEdit = QtGui.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(50, 150, 331, 25)) self.lineEdit.setObjectName(_fromUtf8("lineEdit")) self.label_3 = QtGui.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(50, 200, 81, 18)) self.label_3.setStyleSheet(_fromUtf8("font: 9pt \"Microsoft YaHei UI\";")) self.label_3.setObjectName(_fromUtf8("label_3")) self.lineEdit_2 = QtGui.QLineEdit(self.centralwidget) self.lineEdit_2.setGeometry(QtCore.QRect(50, 230, 331, 25)) self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2")) self.label_4 = QtGui.QLabel(self.centralwidget) self.label_4.setGeometry(QtCore.QRect(50, 280, 81, 18)) self.label_4.setStyleSheet(_fromUtf8("font: 9pt \"Microsoft YaHei UI\";")) self.label_4.setObjectName(_fromUtf8("label_4")) self.lineEdit_3 = QtGui.QLineEdit(self.centralwidget) self.lineEdit_3.setGeometry(QtCore.QRect(50, 310, 331, 25)) self.lineEdit_3.setObjectName(_fromUtf8("lineEdit_3")) self.pushButton = QtGui.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(50, 380, 112, 34)) self.pushButton.setStyleSheet(_fromUtf8("font: 9pt \"Microsoft YaHei UI\";\n" "background-color: rgb(215, 215, 215);")) self.pushButton.setObjectName(_fromUtf8("pushButton")) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 747, 30)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) self.label.setText(_translate("MainWindow", "欢迎注册", None)) self.label_2.setText(_translate("MainWindow", "名字", None)) self.label_3.setText(_translate("MainWindow", "密码", None)) self.label_4.setText(_translate("MainWindow", "重复密码", None)) self.pushButton.setText(_translate("MainWindow", "注册", None)) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_MainWindow() ui.setupUi(Form) Form.show() sys.exit(app.exec_()) Traceback (most recent call last): File "D:/PyCharm 2016.2.3/example/Sign.py", line 88, in <module> ui.setupUi(Form) File "D:/PyCharm 2016.2.3/example/Sign.py", line 64, in setupUi MainWindow.setCentralWidget(self.centralwidget) AttributeError: 'QWidget' object has no attribute 'setCentralWidget'

Keras测试错误'ProgbarLogger' no attribute 'log_values'

Keras 简单程序测试,出现如下错位,请问如何解决: Apple@Host~/test$ python3 kt.py Using Theano backend. -------------------------------------------------- Iteration 1 Train on 0 samples, validate on 0 samples Epoch 1/2 Traceback (most recent call last): File "ktest2.py", line 189, in <module> model.fit(inputs, labels, batch_size=batch_size, nb_epoch=2, validation_split = 0.1) File "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 672, in fit initial_epoch=initial_epoch) File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 1196, in fit initial_epoch=initial_epoch) File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 911, in _fit_loop callbacks.on_epoch_end(epoch, epoch_logs) File "/usr/local/lib/python3.5/dist-packages/keras/callbacks.py", line 76, in on_epoch_end callback.on_epoch_end(epoch, logs) File "/usr/local/lib/python3.5/dist-packages/keras/callbacks.py", line 265, in on_epoch_end self.progbar.update(self.seen, self.log_values, force=True) AttributeError: 'ProgbarLogger' object has no attribute 'log_values' Apple@Host:~/test$

python程序报错缓冲读取器没有convert属性

**这是报错信息** ``` Traceback (most recent call last): File "E:\web\test\image_processing.py", line 25, in <module> to_black_white("test1.jpg",100) File "E:\web\test\image_processing.py", line 7, in to_black_white img = img.convert('L') AttributeError: '_io.TextIOWrapper' object has no attribute 'convert' [Finished in 0.3s with exit code 1] [shell_cmd: python -u "E:\web\test\image_processing.py"] [dir: E:\web\test] [path: C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Users\梦殇空城\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\梦殇空城\AppData\Local\Programs\Python\Python36-32\;C:\Users\梦殇空城\AppData\Local\Microsoft\WindowsApps;D:\PyCharm 2018.3.5\bin;] ``` 这是源码 ``` from PIL import Image, ImageFilter def to_black_white(file_name,threshold): #打开图片 img = open(file_name) # 转灰度 img = img.convert('L') #锐化 img = img.filter(ImageFilter.SHARPEN) #遍历像素 for y in range(height): for x in range(width): pixel = img.getpixel((x,y)) if pixel > threshold: img.putpixel((x,y),(255)) else: img.putpixel((x,y),(0)) # 保存图片 img.save('BW_'+file_name) to_black_white("test1.jpg",100) ``` 求大神解决

celery 启动worker 时候报错

错误信息如下: raceback (most recent call last): File "/home/xuxiaolong/anaconda3/lib/python3.6/site-packages/celery/app/utils.py", line 228, in find_app found = sym.app AttributeError: module 'celeryDemo' has no attribute 'app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/xuxiaolong/anaconda3/bin/celery", line 11, in <module> sys.exit(main()) File "/home/xuxiaolong/anaconda3/lib/python3.6/site-packages/celery/__main__.py", line 30, in main main() File "/home/xuxiaolong/anaconda3/lib/python3.6/site-packages/celery/bin/celery.py", line 80, in main cmd.execute_from_commandline(argv) File "/home/xuxiaolong/anaconda3/lib/python3.6/site-packages/celery/bin/celery.py", line 723, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/xuxiaolong/anaconda3/lib/python3.6/site-packages/celery/bin/base.py", line 301, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/home/xuxiaolong/anaconda3/lib/python3.6/site-packages/celery/bin/base.py", line 431, in setup_app_from_commandline self.app = self.find_app(app) File "/home/xuxiaolong/anaconda3/lib/python3.6/site-packages/celery/bin/base.py", line 451, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/home/xuxiaolong/anaconda3/lib/python3.6/site-packages/celery/app/utils.py", line 233, in find_app found = sym.celery AttributeError: module 'celeryDemo' has no attribute 'celery' 代码目录结构: celeryDemo --__init__.py --tasks.py --CeleryConf.py --config.py **config.py代码:** from __future__ import absolute_import CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/5' BROKER_URL = 'redis://127.0.0.1:6379/6' **celeryconf.py代码**: from __future__ import absolute_import from celery import Celery app=Celery('celeryDemo', include=['celeryDemo.tasks']) app.config_from_object('celeryDemo.config') if __name__ == '__main__': app.start() **tasks.py代码:** from __future__ import absolute_import from celeryDemo.celeryConf import app #from celeryDemo.scrapyLijia import scrapyProcess @app.task def add(x, y): return x + y """ @app.task def spider(region): q =[] process = scrapyProcess(region,q,"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0",None,5) process.start() """ 当家帮忙看下,我查了好久不知道啥问题

python提交commit()错误

![图片说明](https://img-ask.csdn.net/upload/201803/15/1521126207_767529.png) 报错 C:\Python33\python.exe C:/Users/test/sql2.py C:\Python33\lib\site-packages\pymysql\cursors.py:165: Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 480") result = self._query(query) Traceback (most recent call last): File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1193, in _execute_context context) File "C:\Python33\lib\site-packages\sqlalchemy\engine\default.py", line 507, in do_execute cursor.execute(statement, parameters) File "C:\Python33\lib\site-packages\pymysql\cursors.py", line 165, in execute result = self._query(query) File "C:\Python33\lib\site-packages\pymysql\cursors.py", line 321, in _query conn.query(q) File "C:\Python33\lib\site-packages\pymysql\connections.py", line 860, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1061, in _read_query_result result.read() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1349, in read first_packet = self.connection._read_packet() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1018, in _read_packet packet.check_error() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 384, in check_error err.raise_mysql_exception(self._data) File "C:\Python33\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.IntegrityError: (1062, "Duplicate entry '7' for key 'PRIMARY'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:/Users/test/sql2.py", line 25, in <module> session.commit() File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 937, in commit self.transaction.commit() File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 461, in commit self._prepare_impl() File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 441, in _prepare_impl self.session.flush() File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 2237, in flush self._flush(objects) File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 2363, in _flush transaction.rollback(_capture_exception=True) File "C:\Python33\lib\site-packages\sqlalchemy\util\langhelpers.py", line 66, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "C:\Python33\lib\site-packages\sqlalchemy\util\compat.py", line 187, in reraise raise value File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 2327, in _flush flush_context.execute() File "C:\Python33\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 391, in execute rec.execute(self) File "C:\Python33\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 556, in execute uow File "C:\Python33\lib\site-packages\sqlalchemy\orm\persistence.py", line 181, in save_obj mapper, table, insert) File "C:\Python33\lib\site-packages\sqlalchemy\orm\persistence.py", line 830, in _emit_insert_statements execute(statement, multiparams) File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 948, in execute return meth(self, multiparams, params) File "C:\Python33\lib\site-packages\sqlalchemy\sql\elements.py", line 269, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1060, in _execute_clauseelement compiled_sql, distilled_params File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1200, in _execute_context context) File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1413, in _handle_dbapi_exception exc_info File "C:\Python33\lib\site-packages\sqlalchemy\util\compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "C:\Python33\lib\site-packages\sqlalchemy\util\compat.py", line 186, in reraise raise value.with_traceback(tb) File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1193, in _execute_context context) File "C:\Python33\lib\site-packages\sqlalchemy\engine\default.py", line 507, in do_execute cursor.execute(statement, parameters) File "C:\Python33\lib\site-packages\pymysql\cursors.py", line 165, in execute result = self._query(query) File "C:\Python33\lib\site-packages\pymysql\cursors.py", line 321, in _query conn.query(q) File "C:\Python33\lib\site-packages\pymysql\connections.py", line 860, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1061, in _read_query_result result.read() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1349, in read first_packet = self.connection._read_packet() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1018, in _read_packet packet.check_error() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 384, in check_error err.raise_mysql_exception(self._data) File "C:\Python33\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry '7' for key 'PRIMARY'") [SQL: 'INSERT INTO user (id, name) VALUES (%(id)s, %(name)s)'] [parameters: {'id': '7', 'name': 'haha'}] (Background on this error at: http://sqlalche.me/e/gkpj) 进程已结束,退出代码1 虽然报错了,但数据库里还是插入了数据的

Python下的pickle.PicklingError

["thread1", "thread2"]

theano 报错 module 'configparser' has no attribute 'ConfigParser' 用的是Anaconda3 python3.6

>theano 报错 module 'configparser' has no attribute 'ConfigParser' 用的是Win10 Anaconda3 python3.6 ``` from sklearn.datasets import load_boston import theano.tensor as T import numpy as np import matplotlib.pyplot as plt import theano class Layer(object): def __init__(self,inputs,in_size,out_size,activation_function=None): self.W = theano.shared(np.random.normal(0,1,(in_size,out_size))) self.b = theano.shared(np.zeros((out_size,)) + 0.1) self.Wx_plus_b = T.dot(inputs, self.W) + self.b self.activation_function = activation_function if activation_function is None: self.outputs = self.Wx_plus_b else: self.outputs = self.activation_function(self.Wx_plus_b) def minmax_normalization(data): xs_max = np.max(data, axis=0) xs_min = np.min(data, axis=0) xs = (1-0)*(data - xs_min)/(xs_max - xs_min) + 0 return xs np.random.seed(100) x_dataset = load_boston() x_data = x_dataset.data # minmax normalization, rescale the inputs x_data = minmax_normalization(x_data) y_data = x_dataset.target[:,np.newaxis] #cross validation, train test data split x_train, y_train = x_data[:400], y_data[:400] x_test, y_test = x_data[400:], y_data[400:] x = T.dmatrix('x') y = T.dmatrix('y') l1 = Layer(x, 13, 50, T.tanh) l2 = Layer(l1.outputs, 50, 1, None) #compute cost cost = T.mean(T.square(l2.outputs - y)) #cost = T.mean(T.square(l2.outputs - y)) + 0.1*((l1.W**2).sum() + (l2.W**2).sum()) #l2 regulization #cost = T.mean(T.square(l2.outputs - y)) + 0.1*(abs(l1.W).sum() + abs(l2.W).sum()) #l1 regulization gW1, gb1, gW2, gb2 = T.grad(cost, [l1.W,l1.b,l2.W,l2.b]) #gradient descend learning_rate = 0.01 train = theano.function(inputs=[x,y], updates=[(l1.W,l1.W-learning_rate*gW1), (l1.b,l1.b-learning_rate*gb1), (l2.W,l2.W-learning_rate*gW2), (l2.b,l2.b-learning_rate*gb2)]) compute_cost = theano.function(inputs=[x,y], outputs=cost) #record cost train_err_list = [] test_err_list = [] learning_time = [] for i in range(1000): if 1%10 == 0: #record cost train_err_list.append(compute_cost(x_train,y_train)) test_err_list.append(compute_cost(x_test,y_test)) learning_time.append(i) #plot cost history plt.plot(learning_time, train_err_list, 'r-') plt.plot(learning_time, test_err_list,'b--') plt.show() #作者 morvan莫凡 https://morvanzhou.github.io ``` 报错了: Traceback (most recent call last): File "C:/Users/Elena/PycharmProjects/theano/regularization.py", line 1, in <module> from sklearn.datasets import load_boston File "C:\Users\Elena\Anaconda3\lib\site-packages\sklearn\datasets\__init__.py", line 22, in <module> from .twenty_newsgroups import fetch_20newsgroups File "C:\Users\Elena\Anaconda3\lib\site-packages\sklearn\datasets\twenty_newsgroups.py", line 44, in <module> from ..feature_extraction.text import CountVectorizer File "C:\Users\Elena\Anaconda3\lib\site-packages\sklearn\feature_extraction\__init__.py", line 10, in <module> from . import text File "C:\Users\Elena\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 28, in <module> from ..preprocessing import normalize File "C:\Users\Elena\Anaconda3\lib\site-packages\sklearn\preprocessing\__init__.py", line 6, in <module> from ._function_transformer import FunctionTransformer File "C:\Users\Elena\Anaconda3\lib\site-packages\sklearn\preprocessing\_function_transformer.py", line 5, in <module> from ..utils.testing import assert_allclose_dense_sparse File "C:\Users\Elena\Anaconda3\lib\site-packages\sklearn\utils\testing.py", line 61, in <module> from nose.tools import raises as _nose_raises File "C:\Users\Elena\Anaconda3\lib\site-packages\nose\__init__.py", line 1, in <module> from nose.core import collector, main, run, run_exit, runmodule File "C:\Users\Elena\Anaconda3\lib\site-packages\nose\core.py", line 11, in <module> from nose.config import Config, all_config_files File "C:\Users\Elena\Anaconda3\lib\site-packages\nose\config.py", line 6, in <module> import configparser File "C:\Users\Elena\Anaconda3\Lib\site-packages\theano\configparser.py", line 15, in <module> import theano File "C:\Users\Elena\Anaconda3\lib\site-packages\theano\__init__.py", line 88, in <module> from theano.configdefaults import config File "C:\Users\Elena\Anaconda3\lib\site-packages\theano\configdefaults.py", line 17, in <module> from theano.configparser import (AddConfigVar, BoolParam, ConfigParam, EnumStr, File "C:\Users\Elena\Anaconda3\lib\site-packages\theano\configparser.py", line 77, in <module> theano_cfg = (configparser.ConfigParser if PY3 **AttributeError: module 'configparser' has no attribute 'ConfigParser**' 把theano里的configparser.py文件里的ConfigParser改成了configparser还是不行 换了模块import configparsor也不行。。。![图片说明](https://img-ask.csdn.net/upload/201909/30/1569832318_223436.png)

python 爬虫刚开始学习的一个问题

![图片说明](https://img-ask.csdn.net/upload/201709/14/1505379243_392477.png) 这段代码,当我点Execute Selection in Console时候,可以正常运行,并且结果和教材一致 ![图片说明](https://img-ask.csdn.net/upload/201709/14/1505379267_933740.png) 但是我直接运行这个文件时,就开始报错了 ![图片说明](https://img-ask.csdn.net/upload/201709/14/1505379288_263899.png) 这是怎么回事呢?? 错误信息如下: C:\Users\yzy\AppData\Local\Programs\Python\Python36\python.exe C:/Users/yzy/Desktop/python/webscraping.py Traceback (most recent call last): File "C:\Users\yzy\AppData\Local\Programs\Python\Python36\lib\bz2.py", line 19, in <module> from threading import RLock ImportError: cannot import name 'RLock' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/yzy/Desktop/python/webscraping.py", line 4, in <module> from urllib.request import urlopen File "C:\Users\yzy\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 98, in <module> import tempfile File "C:\Users\yzy\AppData\Local\Programs\Python\Python36\lib\tempfile.py", line 43, in <module> import shutil as _shutil File "C:\Users\yzy\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 22, in <module> import bz2 File "C:\Users\yzy\AppData\Local\Programs\Python\Python36\lib\bz2.py", line 21, in <module> from dummy_threading import RLock File "C:\Users\yzy\AppData\Local\Programs\Python\Python36\lib\dummy_threading.py", line 49, in <module> sys_modules['_dummy__threading_local'] = sys_modules['_threading_local'] KeyError: '_threading_local' Exception ignored in: <module 'threading' from 'C:\\Users\\yzy\\Desktop\\python\\threading.py'> AttributeError: module 'threading' has no attribute '_shutdown' Process finished with exit code 1

Windows API 用Python 实现键盘勾取 无效运行(一片空白),这么回事?

# 求帮助,代码如下没有报错 但运行后**没有显示任何内容** ```from ctypes import * import sys from ctypes.wintypes import MSG from ctypes.wintypes import DWORD user32 = windll.user32 kernel32 = windll.kernel32 hook_types = 13 keydown = 0X0100 ctrl = 162 class keylogger: def __init__(self): self.luser32 = user32 self.hooked = None def installhookproc(self,pointer): self.hooked=self.luser32.SetWindowsHookExA( hook_types, pointer, kernel32.GetModuleHandleW(None), 0 ) if not self.hooked: return False return True def uninstallhookproc(self): if self.hooked is None: return self.luser32.UnhookWindowsHookEx(self.hooked) self.hooked=None def getfptr(fn): cm=CFUNCTYPE(c_int,c_int,c_int,POINTER(c_void_p)) return cm(fn) def hookproc(ncode,wp,lp): if wp is not keydown: return user32.CallNextHookEx(keylogger.hooked,ncode,wp,lp) hookedkey=chr(lp[0]) print(hookedkey) #自定义 if int(lp[0]) == ctrl: print("Ctrl pressed,Call uninstallhookproc") keylogger.uninstallhookproc() sys.exit(-1) return user32.CallNextHookEx(keylogger.hooked,ncode,wp,lp) def startkeylog(): msg=MSG() user32.GetMessageA(byref(msg),0,0,0) keylogger=keylogger() pointer=getfptr(hookproc) if keylogger.installhookproc(pointer): print('Installed"') else: print("Something maybe wrong!") startkeylog() ```

python编程从入门到实践,13.4节,Alien检索不到Settings中的速度设置?

``` class Settings(): """存储《外星人入侵的所有设置的类""" def __init__(self): """初始化游戏的设置""" #屏幕设置 self.screen_width = 1000 self.screen_height = 700 self.bg_color = (255,255,255) #飞船的设置 self.ship_speed_factor = 4 #子弹设置 self.bullet_speed_factor = 3 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60,60,60 self.bullets_allowed = 3 # 外星人设置 self.alien_speed_factor = 1 self.fleet_drop_speed = 10 self.fleet_direction = 1 ``` import sys import pygame from pygame.sprite import Group from settings import Settings from ship import Ship from alien import Alien import game_functions as gf def run_game(): # 初始化pygame、设置和屏幕对象 pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption(("Alien Invasion")) # 创建一艘飞船 ship = Ship(ai_settings, screen) # 创建一个用于储存子弹的编组 bullets = Group() # 创建一个外星人 aliens = Group() #创建外星人群 gf.create_fleet(ai_settings,screen,ship,aliens) while True: gf.check_event(ai_settings, screen, ship, bullets) ship.update() gf.update_bullets(bullets) gf.update_aliens(aliens) gf.update_screen(ai_settings, screen, ship, aliens, bullets) run_game() ``` #alien.py import pygame from pygame.sprite import Sprite class Alien(Sprite): def __init__(self,ai_settings, screen ): """初始化外星人并且设置起始位置""" super().__init__() self.ai_settings = ai_settings self.screen = screen #加载外星人图像,并且设置其rect属性 self.image = pygame.image.load('images/alien.bmp') self.rect = self.image.get_rect() #每个外星人最初都在屏幕左上角附近 self.rect.x = self.rect.width self.rect.y = self.rect.height #存储外星人的准确位置 self.x = float(self.rect.x) def blitme(self): """在指定位置绘制外星人""" self.screen.blit(self.image, self.rect) def check_edges(self): """如果外星人出于屏幕边缘,就返回True""" screen_rect = self.screen.get_rect() if self.rect.right >= screen_rect.right: return True elif self.rect.left <= 0: return True def update(self): """向左或者右移动的外星人""" self.x += self.ai_settings.alien_speed_factor self.rect.x = self.x ``` import sys import pygame from bullet import Bullet from alien import Alien def check_keydown_events(event, ai_settings, screen, ship, bullets): """响应按键""" if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: fire_bullet(ai_settings, screen, ship, bullets) def fire_bullet(ai_settings,screen,ship,bullets): """如果没达到限制,就发射一颗子弹""" # 创建新的子弹,并将其加入到编组bullets中 if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) def check_keyup_events(event,ship): if event.key == pygame.K_RIGHT: ship.moving_right = False elif event.key == pygame.K_LEFT: ship.moving_left = False def check_event(ai_settings, screen, ship, 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) def update_screen(ai_settings,screen,ship,aliens,bullets): """更新屏幕上的图像,并切换到新屏幕""" # 让每次绘制的屏幕都可见 screen.fill(ai_settings.bg_color) #在飞船和外星人后面重绘所有子弹 for bullet in bullets.sprites(): bullet.draw_bullet() ship.blitme() aliens.draw(screen) # 让每次绘制的屏幕都可见 pygame.display.flip() def update_bullets(bullets): """更新子弹位置,并删除已消失的子弹""" # 更新子弹位置 bullets.update() for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) print(len(bullets)) # 让每次绘制的屏幕都可见 pygame.display.flip() def get_number_aliens_x(ai_settings, alien_width): """计算每行能容纳的外星人""" available_space_x = ai_settings.screen_width - 2 * alien_width number_aliens_x = int(available_space_x / (2 * alien_width)) return number_aliens_x def get_number_rows(ai_settings,ship_height,alien_height): available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height) number_rows = int(available_space_y / (2 * alien_height)) return number_rows def create_aliens(ai_settings, screen, aliens,alien_number,row_number): """创建一个外星人置于当行""" alien = Alien(ai_settings, screen) alien_width = alien.rect.width alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number aliens.add(alien) def create_fleet(ai_settings,screen,ship,aliens): """创建外星人群""" # 创建一个外星人,并计算一行可容纳多少个外星人 alien = Alien(ai_settings,screen) number_aliens_x = get_number_aliens_x(ai_settings,alien.rect.width) number_rows = get_number_rows(ai_settings,ship.rect.height,alien.rect.height) for row_number in range(number_rows): for alien_number in range(number_aliens_x): # 创建一个外星人并将其加入当前行 create_aliens(alien,screen,aliens,alien_number,row_number) def update_aliens(aliens): """ 检查是否外星人位于屏幕边缘,并更新外星人群中所有外星人的位置 """ aliens.update() ``` ```

学Python后到底能干什么?网友:我太难了

感觉全世界营销文都在推Python,但是找不到工作的话,又有哪个机构会站出来给我推荐工作? 笔者冷静分析多方数据,想跟大家说:关于超越老牌霸主Java,过去几年间Python一直都被寄予厚望。但是事实是虽然上升趋势,但是国内环境下,一时间是无法马上就超越Java的,也可以换句话说:超越Java只是时间问题罢。 太嚣张了会Python的人!找工作拿高薪这么简单? https://edu....

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

为什么程序猿都不愿意去外包?

分享外包的组织架构,盈利模式,亲身经历,以及根据一些外包朋友的反馈,写了这篇文章 ,希望对正在找工作的老铁有所帮助

Java校招入职华为,半年后我跑路了

何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

@程序员:GitHub这个项目快薅羊毛

今天下午在朋友圈看到很多人都在发github的羊毛,一时没明白是怎么回事。 后来上百度搜索了一下,原来真有这回事,毕竟资源主义的羊毛不少啊,1000刀刷爆了朋友圈!不知道你们的朋友圈有没有看到类似的消息。 这到底是啥情况? 微软开发者平台GitHub 的一个区块链项目 Handshake ,搞了一个招募新会员的活动,面向GitHub 上前 25万名开发者派送 4,246.99 HNS币,大约价...

用python打开电脑摄像头,并把图像传回qq邮箱【Pyinstaller打包】

前言: 如何悄悄的打开朋友的摄像头,看看她最近过的怎么样,嘿嘿!这次让我带你们来实现这个功能。 注: 这个程序仅限在朋友之间开玩笑,别去搞什么违法的事情哦。 代码 发送邮件 使用python内置的email模块即可完成。导入相应的代码封装为一个send函数,顺便导入需要导入的包 注: 下面的代码有三处要修改的地方,两处写的qq邮箱地址,还有一处写的qq邮箱授权码,不知道qq邮箱授权码的可以去百度一...

做了5年运维,靠着这份监控知识体系,我从3K变成了40K

从来没讲过运维,因为我觉得运维这种东西不需要太多的知识面,然后我一个做了运维朋友告诉我大错特错,他就是从3K的运维一步步到40K的,甚至笑着说:我现在感觉自己什么都能做。 既然讲,就讲最重要的吧。 监控是整个运维乃至整个产品生命周期中最重要的一环,事前及时预警发现故障,事后提供详实的数据用于追查定位问题。目前业界有很多不错的开源产品可供选择。选择一款开源的监控系统,是一个省时省力、效率最高的方...

C++(继承):19---虚基类与虚继承(virtual)

一、菱形继承 在介绍虚继承之前介绍一下菱形继承 概念:A作为基类,B和C都继承与A。最后一个类D又继承于B和C,这样形式的继承称为菱形继承 菱形继承的缺点: 数据冗余:在D中会保存两份A的内容 访问不明确(二义性):因为D不知道是以B为中介去访问A还是以C为中介去访问A,因此在访问某些成员的时候会发生二义性 缺点的解决: 数据冗余:通过下面“虚继承”技术来解决(见下) 访问...

再不跳槽,应届毕业生拿的都比我多了!

跳槽几乎是每个人职业生涯的一部分,很多HR说“三年两跳”已经是一个跳槽频繁与否的阈值了,可为什么市面上有很多程序员不到一年就跳槽呢?他们不担心影响履历吗? PayScale之前发布的**《员工最短任期公司排行榜》中,两家码农大厂Amazon和Google**,以1年和1.1年的员工任期中位数分列第二、第四名。 PayScale:员工最短任期公司排行榜 意外的是,任期中位数极小的这两家公司,薪资...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

win10暴力查看wifi密码

刚才邻居打了个电话说:喂小灰,你家wifi的密码是多少,我怎么连不上了。 我。。。 我也忘了哎,就找到了一个好办法,分享给大家: 第一种情况:已经连接上的wifi,怎么知道密码? 打开:控制面板\网络和 Internet\网络连接 然后右击wifi连接的无线网卡,选择状态 然后像下图一样: 第二种情况:前提是我不知道啊,但是我以前知道密码。 此时可以利用dos命令了 1、利用netsh wlan...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

女朋友过生日,我花了20分钟给她写了一个代理服务器

女朋友说:“看你最近挺辛苦的,我送你一个礼物吧。你看看想要什么,我来准备。” 我想了半天,从书到鞋子到电子产品最后到生活用品,感觉自己什么都不缺,然后和她说:“你省省钱吧,我什么都不需要。” 她坚持要送:“不行,你一定要说一个礼物,我想送你东西了。” 于是,我认真了起来,拿起手机,上淘宝逛了几分钟,但还是没能想出来缺点什么,最后实在没办法了:“这样吧,如果你实在想送东西,那你就写一个代理服务器吧”...

记一次腾讯面试,我挂在了最熟悉不过的队列上……

腾讯后台面试,面试官问:如何自己实现队列?

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

立即提问
相关内容推荐