会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 133764个问题
Python 全系列/第二阶段:Python 深入与提高/文件处理 2491楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 2492楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 2493楼

# coding=utf-8
"""
新增功能:
    左上角文字绘制:
    左上角输出敌方坦克的数量6
"""
#导入pygame模块
import pygame
SCREEN_WIDTH=700      #窗口的大小是常量
SCREEN_HEIGHT=500
BG_COLOR=pygame.Color(0,0,0)    #窗口填充色:黑色
TEXT_COLOR=pygame.Color(255,0,0)        #字体颜色;红色
class MainGame():
    window=None     #定义窗口对象,初始化为None,属于类对象
    def __init__(self):
        pass
    #开始游戏
    def startGame(self):
        #加载主窗口
        pygame.display.init()   #初始化窗口(显示窗口)
        #设置窗口的大小及显示
        MainGame.window=pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
        #窗口大小作为列表传进去,返回一个对象surface,传给窗口对象
        #MainGame.window 调用用类名.类属性
        # 设置窗口标题
        pygame.display.set_caption("坦克大战1.03")
        while True:
            # 给窗口设置填充色,用surface里面的fill方法
            MainGame.window.fill(BG_COLOR)
            #获取事件
            self.getEvent()
            #绘制文字
            MainGame.window.blit(self.getTextSurface("敌方坦克剩余数量%d"%6),(10,10))
            #(10,10)表示小的surface在窗口window中的位置
            pygame.display.update()  # 窗口一直显示
            #点击x窗口关闭不了

    #结束游戏
    def endGame(self):
        print("谢谢使用,欢迎再次使用")
        exit()
    #左上角文字的绘制
    def getTextSurface(self,text):   #text指敌方坦克数量,变化量
        #初始化字体模块
        pygame.font.init()
        #查看所有的字体名称
        #print(pygame.font.get_fonts())
        #获取字体Font对象
        font=pygame.font.SysFont("kaiti",18)
        #绘制文本信息
        textSurface=font.render(text,True,TEXT_COLOR)
        return textSurface

    #获取事件
    def getEvent(self):
        #获取所有事件
        eventList = pygame.event.get()
        #遍历事件
        for event in eventList:
            #判断按下的键是关闭还是键盘按下
            #如果按的是退出,关闭窗口
            if event.type == pygame.QUIT:
                self.endGame()
            #如果是键盘的按下
            if event.type == pygame.KEYDOWN:
                #判断按下的是上、下、左、右
                if event.key == pygame.K_LEFT:
                    print("按下左键,坦克向左移动")
                elif event.key == pygame.K_RIGHT:
                    print("按下右键,坦克向右移动")
                elif event.key == pygame.K_UP:
                    print("按下上键,坦克向上移动")
                elif event.key == pygame.K_DOWN:
                    print("按下下键,坦克向下移动")




class Tank():
    def __init__(self):
        pass
    #移动
    def move(self):
        pass
    #射击
    def shot(self):
        pass
    #展示坦克的方法
    def dispaliTank(self):
        pass
#我方坦克
class MyTank(Tank):
    def __init__(self):
        pass
#敌方坦克
class EnemyTank(Tank):
    def __init__(self):
        pass

class Bullet():
    def __init__(self):
        pass
    #移动类
    def move(self):
        pass
    #展示子弹的方法
    def displayBullet(self):
        pass

class Wall():
    def __init__(self):
        pass
    #展示墙壁的方法
    def displayWall(self):
        pass

class Explode():
    def __init__(self):
        pass
    #展示爆炸的方法
    def displayExplode(self):
        pass

class Music():
    def __init__(self):
        pass
    #播放音乐的方法
    def play(self):
        pass

if __name__=="__main__":
    #MainGame().startGame()       #调用startGame()方法显示窗口对象
    #窗口对象只显示一次就关闭
    MainGame().getTextSurface()


老师,我上面的代码为什么出现以下报错

Traceback (most recent call last):
  File "F:/py/tank/tank05.py", line 134, in <module>
Hello from the pygame community. https://www.pygame.org/contribute.html
    MainGame().getTextSurface()
TypeError: getTextSurface() missing 1 required positional argument: 'text'


Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 2494楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 2495楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 2496楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 2497楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 2500楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 2501楼

youbian.txt

老师,上面是 youbian.txt 文档的附件,下面是我写的代码,为什么不管输入邮编是否含有都显示无此邮编,我是哪里错了吗?貌似最后的 finally 内容也是错的

# 读取 youbian.txt 文件中的数据,完成查询操作,输入邮政编号
# 如果有此编号,输出对应的城市,否则提示,无此邮编
m = eval(input('请输入邮编:'))
try:
    file = open('youbian.txt','r')
    lists = file.readlines()
    for x in lists:
        if x[0] == m:
            print(x[1])
    else:print('无此邮编')
except Exception as e:
    print(e)
finally:
    file.close()


Python 全系列/第二阶段:Python 深入与提高/异常机制 2503楼

老师,问题如下图:

ZB0SM8]]BI(Z@SUJTN605ZW.png

from tkinter import *
from tkinter import messagebox
import webbrowser


class Application(Frame):
    '''一个经典的GUI程序的类的写法'''

    def __init__(self, master=None):
        super(Application, self).__init__(master)           #super()代表的是父类的定义,而不是父类的对象/虽然继承了Frame,但不会调用Frame的构造器
        self.master = master
        self.pack()
        self.createwidget()                #需要创建多个窗口对象时,需要调用此


    def createwidget(self):
        '''创建组件'''
        self.w1 = Text(root, width=40, height=12, bg='gray')  #40列字符  12行字符的高度
        #宽度 20个字母(10个汉字),高度一个行高
        self.w1.pack()

        self.w1.insert(1.0, '123456789\nabcdefg')
        self.w1.insert(2.3, '锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦\n')

        Button(self, text='重复插入文本', command=self.insertTest).pack(side='left')  #若写’left‘,默认垂直排列
        Button(self, text='返回文本', command=self.returnTest).pack(side='left')
        Button(self, text='添加图片', command=self.addImage).pack(side='left')
        Button(self, text='添加组件', command=self.addWidget).pack(side='left')
        Button(self, text='通过tag精确控制文本',command=self.bindTag).pack(side='left')


        def insertTest(self):
            # INSERT 索引表示在光标处插入
            self.w1.insert(INSERT, 'gaoqi')
            # END索引号表示在最后插入
            self.w1.insert(END, '[sxt]')
            self.w1.insert(1.8, 'gaoqi')

        def retuRntest(self):
            # Indexes(索引)是用来指向Text组件中的文本的位置,Text组件索引也是对应实际字符之间的位置
            # 核心:行号以1开始,列好以0开始
            print(self.w1.get(1.2, 1.6))
            print('所有文本内容:\n'+self.w1.get(1.0, END))  # 将文本内容返回到Run框中

        def addImage(self):
            global photo
            self.photo = PhotoImage(file='imgs/星球.gif')
            self.w1.image_create(END, image=self.photo)

        def addWidget(self):   #增加组件
            b1 = Button(self.w1, text='爱尚学堂')
            #在text 创建组件的命令
            self.w1.window_create(INSERT, window=b1)

        def bindTag(self):
            self.w1.delete(1.0,END)
            self.w1.insert(INSERT, 'good good study,day day up!\n北京尚学堂\n'
                                   '百战程序员\n百度,搜一下就知道')
            self.w1.tag_add('good', 1.0, 1.9)      #给’1.0‘到’1.9‘增加一个标记,’good‘或其他也可以
            self.w1.tag_config('good', background='yellow', foreground='red')
            #config 给标记处增加配置

            self.w1.tag_add('baidu', 4.0, 4.2)
            self.w1.tag_config('baidu', underground=True)   #加了下划线
            self.w1.tag_bind('baidu', '<Button-1>', self.webshow)
            #bind 绑定事件

        def webshow(self, event):
            webbrowser.open('http://www.baidu.com')


if __name__=='__main__':     # 规范写法,作为独立的个体去调用
    root = Tk()
    root.geometry('400x300+200+300')
    app = Application(master=root)
    root.mainloop()


Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2505楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637