首页 新闻 会员 周边

python自己写的类无法创建实例

0
[已解决问题] 解决于 2018-04-06 21:04
 1 # coding=gbk
 2 import pygame
 3 from button_game.setting import Settings
 4 from button_game import game_functions as gf
 5 from button_game.button import Button
 6 
 7 
 8 def run_game():
 9     pygame.init()
10     button_setting = Settings()
11     # 开始设置屏幕
12     screen = pygame.display.set_mode(button_setting.screen_width, button_setting.screen_height)
13     screen.display.set_caption("按键")
14     button = Button(button_setting, screen)
15 
16 
17 while True:
18     gf.check_events(button)

 

这是我自己写的python代码,其中Button是自己写的类,然后在创建实例的时候总是报错。

# coding=gbk 


class Button():
    def __init__(self, button_setting, screen):
        self.button_setting = button_setting
        self.screen = screen
        self.event_key = ''
        self.screen_rect = screen.get_rect()

    def blitme(self):
        self.screen.blit(self.event_key, self.screen_rect.center)

这是Button类和提示的报错。我在网上也看过类似的问题,有的说是因为Pycharm的源文件夹设置有问题(的确,我是这个程序是在第二级的python package中), 单位哦改过了,还是不行。

问题补充:
1 F:\软件\Python\python.exe D:/alien_invasion/button_game/button_game.py
2 Traceback (most recent call last):
3   File "D:/alien_invasion/button_game/button_game.py", line 3, in <module>
4     from button_game.setting import Settings
5   File "D:\alien_invasion\button_game\button_game.py", line 3, in <module>
6     from button_game.setting import Settings
7 ModuleNotFoundError: No module named 'button_game.setting'; 'button_game' is not a package
8 
9 Process finished with exit code 1

这是我的traceback,看不太懂

这是 具体的文件路径

 

 

还是飘红呀

 

六月香樟的主页 六月香樟 | 菜鸟二级 | 园豆:212
提问于:2018-03-31 10:42

具体报什么错误?

dudu 6年前

@dudu: 你好,自己写的类不能创建实例,我补充了traceback

六月香樟 6年前
< >
分享
最佳答案
0

你是否应该在'button_game'这个文件夹下创建一个'__init__.py'文件?

奖励园豆:5
Masako | 小虾三级 |园豆:1893 | 2018-04-03 10:00

有这个文件,系统默认生成的,创建python package的时候就已经自动生成了

六月香樟 | 园豆:212 (菜鸟二级) | 2018-04-03 21:06

@六月香樟: 你的第一份代码是叫做button_game.py吗?好像是你的代码将'button_game'认为是模块(button_game.py)而不是包(\button_game)了,如果你的Button类在'\button_game'这个文件夹中的'button.py'文件中,可以直接使用"from button import Button"导入.

具体可以发一下你的文件结构吗?你这个应该不是类的问题,是import的问题

Masako | 园豆:1893 (小虾三级) | 2018-04-04 09:40

@Masako: 我已经补充了文件结构,麻烦看下

六月香樟 | 园豆:212 (菜鸟二级) | 2018-04-04 10:24

@六月香樟:你把button_game.py改一个名字,不要和包同名.

Masako | 园豆:1893 (小虾三级) | 2018-04-04 11:22
其他回答(1)
0

原来是我while那一行没有缩进

六月香樟 | 园豆:212 (菜鸟二级) | 2018-04-06 21:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册