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

from tkinter import *
import webbrowser

class Application(Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.creatWidget()

    def creatWidget(self):
        self.tcl = Text(root, width=60, height=20, bg='blue', fg='white')  # 宽度代表100个字符(50个字符)
        self.tcl.pack()
        self.tcl.insert(1.0, '0123456789\nabcdefghijklmn')  # 1.0代表第1行,第0列;2.5代表第2行,第5列插入字符
        self.tcl.insert(2.5, '\n君问归期未有期,\n巴山夜雨涨秋池。\n何当共剪西窗烛,\n却话巴山夜雨时。\n')

        self.tcl.btn01 = Button(self, text='重复插入文本', command=self.insertText)
        self.tcl.btn01.pack(side='left')
        Button(self, text='返回文本', command=self.returnText).pack(side='left')   # 缺点是没有变量引用,只能引用一次
        self.tcl.btn02 = Button(self, text='添加图片', command=self.addImage)
        self.tcl.btn02.pack(side='left')
        self.tcl.btn03 = Button(self, text='添加组件', command=self.addWidget)
        self.tcl.btn03.pack(side='left')
        self.tcl.btn05 = Button(self, text='通过tag精确控制文本', command=self.testTag)
        self.tcl.btn05.pack(side='left')

    def insertText(self):
        self.tcl.insert(INSERT, '惠州')   # 在光标处插入
        self.tcl.insert(END, '广州')     # 在最后插入
        self.tcl.insert(10.2, 'Ongoing')   # 在第10行,第2行插入

    def returnText(self):
        # Indexes(索引)是用来指向Text组件中文本的位置, Text的组件索引也是对应实际字符之间的位置。
        # 核心:行号以1开始,列号以0开始
        print(self.tcl.get(2.2, 2.5))  # 打印第2行 第2列到第5列的内容
        print('所有内容:\n'+self.tcl.get(1.0, END))

    def addImage(self):
        self.photo = PhotoImage(file='‪E:/Photo/Rain.gif')
        self.tcl.image_create(END, image=self.photo)

    def addWidget(self):
        btn04 = Button(self.tcl, text='深圳深圳')
        self.tcl.window_create(INSERT, window=btn04)

    def testTag(self):
        self.tcl.delete(1.0, END)
        self.tcl.insert(INSERT, 'good good study,day day up!\n广州&深圳&惠州\n百度,搜一下就知道')
        self.tcl.tag_add(' ', 1.0, 1.9)
        self.tcl.tag_config(' ', background='yellow', foreground='blue')
        self.tcl.tag_add('飞机', 3.0, 3.2)
        self.tcl.tag_config('飞机', underline=True)
        self.tcl.tag_bind('飞机', '<Button-1>', self.webshow)

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

if __name__ == '__main__':
    root = Tk()
    root.geometry('600x500+100+100')
    root.title('广东之旅')
    app = Application(master=root)
    root.mainloop()

老师,有两个问题想咨询一下:

1、加载图片时提示无法打开,_tkinter.TclError: couldn't open "‪E:/Photo/Rain.gif": no such file or directory,我看我写的路径是对的

image.png

2、tag_add只能将对应定义的‘飞机’的属性赋给定义的3.0-3.2中‘百度’的字符,无法替换掉定义的3.0-3.2之间的字符,定义时‘飞机’这个字符是什么都不重要,与Config、Bind中对应即可,老师是这样吗

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

新增功能:
  1.敌方tank自由移动
'''
 #导入pygame模块

import pygame,time
import random
_display=pygame.display
COLOR_BLACK=pygame.Color(0,0,0)
COLOR_RED=pygame.Color(255,255,255)
class MainGame():
    #游戏主窗口
    window=None
    TANK_P1=None
    SCREEN_HEIGHT=500
    SCREEN_WIDTH=800
    EnemyTank_list=[]
    EnemyTank_count=5
    def __init__(self):
        pass
    def startGame(self):
        _display.init()
        #创建窗口加载窗口
        MainGame.window=_display.set_mode([MainGame.SCREEN_WIDTH,MainGame.SCREEN_HEIGHT])
        MainGame.TANK_P1 = Tank(400, 300)
        # 生成敌方tank
        self.createEnemyTank()
        #设置一下游戏标题
        _display.set_caption("坦克大战v1.03")

        while True:
            # 使用坦克移动的速度慢一点
            time.sleep(0.02)
            MainGame.window.fill(COLOR_BLACK)
            # 获取事件
            self.getEvent()
            #将绘制文字得到的小画布,粘贴到窗口中
            MainGame.window.blit(self.getTextface("剩余敌方坦克%d辆"%5),(5,5))

            #展示tank
            MainGame.TANK_P1.displayTank()

            #循环展示敌方tank
            self.displayEnemyTank()
            # 增加tank的开关,控制其移动
            if MainGame.TANK_P1.stop == False:
                MainGame.TANK_P1.move()
            #窗口的刷新   #让窗口持续刷新操作
            _display.update()


    def createEnemyTank(self):
        top = 100
        # 循环生成敌方坦克
        for i in range(MainGame.EnemyTank_count):
            left = random.randint(0, 600)
            speed = random.randint(1, 4)
            eTank = EnemyTank(left, top, speed)
            MainGame.EnemyTank_list.append(eTank)


   #循环展示敌方tank
    def displayEnemyTank(self):
        for eTank in MainGame.EnemyTank_list:
            eTank.displayTank()
            # tank的移动方法
            eTank.randMove()

    def endGame(self):
        print("谢谢使用")
        #结束python解释器
        exit()

    #添加左上角提示文字
    def getTextface(self,text):
        #初始化字体模块
        pygame.font.init()
        font=pygame.font.SysFont('kaiti',18)
        #使用对应的字符完成相关内容的绘制
        textSurface=font.render(text,True,COLOR_RED)
        return textSurface

#获取程序期间所有事件(鼠标事件,键盘事件)
    def getEvent(self):
        #获取所有事件
        eventList=pygame.event.get()
        #对事件进行判断
        for event in eventList:
    #判断事件是否是quit,如果是,退出
            if event.type==pygame.QUIT:
                self.endGame()
    #判断事件类型是否是按键按下
            if event.type==pygame.KEYDOWN:
     #具体是哪一个按键的处理
                if event.key==pygame.K_LEFT:
                    print("坦克向左掉头,移动")
                    #修改方向
                    MainGame.TANK_P1.direction='L'
                    MainGame.TANK_P1.stop=False
                    # MainGame.TANK_P1.move()
                if event.key==pygame.K_RIGHT:
                    print("坦克向右掉头,移动")
                    #修改方向
                    MainGame.TANK_P1.direction='R'
                    MainGame.TANK_P1.stop=False
                    # MainGame.TANK_P1.move()
                if event.key == pygame.K_UP:
                        print("坦克向上掉头,移动")
                        # 修改方向
                        MainGame.TANK_P1.direction = 'U'
                        MainGame.TANK_P1.stop = False
                        # MainGame.TANK_P1.move()
                if event.key == pygame.K_DOWN:
                            print("坦克向下掉头,移动")
                            # 修改方向
                            MainGame.TANK_P1.direction = 'D'
                            MainGame.TANK_P1.stop = False
                            # MainGame.TANK_P1.move()
                elif event.key==pygame.K_SPACE:
                    print("发射子弹")


             # 结束游戏方法
            if event.type==pygame.KEYUP:
                    #松开的是方向键,才更改移动开关状态
                    if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT or \
                        event.key == pygame.K_UP or event.key==pygame.K_DOWN:
                     #修改坦克的移动状态
                         MainGame.TANK_P1.stop=True


#坦克类
class Tank():
    def __init__(self,left,top):
        self.images={
            'U':pygame.image.load('img/p1tankU.gif'),
            'D': pygame.image.load('img/p1tankD.gif'),
            'L': pygame.image.load('img/p1tankL.gif'),
            'R': pygame.image.load('img/p1tankR.gif')
        }

        self.direction='U'
        self.image=self.images[self.direction]
        #坦克所在的区域
        self.rect=self.image.get_rect()
        #指定坦克初始化位置  分别距x,y轴的位置
        self.rect.left=left
        self.rect.top=top
        #设置tank的开关
        self.stop = True
        #设置tank的速度
        self.speed=4

     #展示坦克(将坦克这个surface绘制到窗口中blit())
    def displayTank(self):
        #1.重新设置tank 的图片
        self.image=self.images[self.direction]
        #2.将坦克加入到窗口中
        MainGame.window.blit(self.image,self.rect)


#坦克中添加速度属性,实现坦克移动
    def move(self):
        if self.direction=='L':
            if self.rect.left>0:
                self.rect.left-=self.speed
        elif self.direction=='R':
            if self.rect.left+self.rect.width<MainGame.SCREEN_WIDTH:
                self.rect.left+=self.speed
        elif self.direction=='U':
            if self.rect.top > 0:
                 self.rect.top-=self.speed
        elif self.direction=='D':
            if self.rect.top + self.rect.height< MainGame.SCREEN_HEIGHT:
                self.rect.top += self.speed

    def hitWalls(self):
        pass
    def shot(self):
        pass
    def display(self):
        pass

    #我方坦克
class MyTank(Tank):
    def __init__(self):
        pass
    def hitEnemyTank(self):
        pass


#完善tank类
#敌方坦克类
class EnemyTank(Tank):

    def __init__(self,left,top,speed):
        #加载图片集
        self.images={
            'U':pygame.image.load('img/enemy1U.gif'),
            'D':pygame.image.load('img/enemy1D.gif'),
            'L':pygame.image.load('img/enemy1L.gif'),
            'R':pygame.image.load('img/enemy1R.gif')
        }
        #方向,随机生成敌方坦克的方向
        self.direction=self.randDirection()
        #根据方向获取图片
        self.image=self.images[self.direction]
        #区域
        self.rect=self.image.get_rect()
        #对left和top进行赋值
        self.rect.left=left
        self.rect.top=top
        #速度
        self.speed=speed
        #移动开关键
        self.stop=True
        #薪增加一个步数变量 step
        self.step=50

     #建立随机生成enemytank的四个方向
    def randDirection(self):
            num=random.randint(1,4)
            if num==1:
                 return 'U'
            if num == 2:
                return 'D'
            if num == 3:
                return 'L'
            if num == 1:
                return 'R'

    #实现敌方tank的自由移动
    def randMove(self):
        if self.step<=0:
            self.direction=self.randDirection()
            self.step=50
        else:
            self.move()
            self.step-=1


    def hitMyTank(self):
        pass


#子弹类
class Bullet():
    def __init__(self):
        pass
    def bulletMove(self):
        pass
    def displayBullet(self):
        pass
    def hitEnemyTank(self):
        pass
    def hitMyTank(self):
        pass
    def hitWalls(self):
        pass

#墙壁类
class Wall():
    def __init__(self):
        pass
    def displayWalls(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()


Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1329楼

pygame,time
random
_display=pygame.display
COLOR_BLACK=pygame.Color(,,)
COLOR_RED=pygame.Color(,,)
():
    window=TANK_P1=SCREEN_HEIGHT=SCREEN_WIDTH=EnemyTank_list=[]
    EnemyTank_count=():
        ():
        _display.init()
        MainGame.window=_display.set_mode([MainGame.SCREEN_WIDTH,MainGame.SCREEN_HEIGHT])
        MainGame.TANK_P1 = Tank(, )
        .createEnemyTank()
        _display.set_caption()

        :
            time.sleep()
            MainGame.window.fill(COLOR_BLACK)
            .getEvent()
            MainGame.window.blit(.getTextface(%),(,))

            MainGame.TANK_P1.displayTank()

            .displayEnemyTank()
            MainGame.TANK_P1.stop == :
                MainGame.TANK_P1.move()
            _display.update()


    ():
        top = i (MainGame.EnemyTank_count):
            left = random.randint(, )
            speed = random.randint(, )
            eTank = EnemyTank(left, top, speed)
            MainGame.EnemyTank_list.append(eTank)


   ():
        eTank MainGame.EnemyTank_list:
            eTank.displayTank()
            eTank.randMove()

    ():
        ()
        ()

    (,text):
        pygame.font.init()
        font=pygame.font.SysFont(,)
        textSurface=font.render(text,,COLOR_RED)
        textSurface

():
        eventList=pygame.event.get()
        event eventList:
    event.type==pygame.QUIT:
                .endGame()
    event.type==pygame.KEYDOWN:
     event.key==pygame.K_LEFT:
                    ()
                    MainGame.TANK_P1.direction=MainGame.TANK_P1.stop=event.key==pygame.K_RIGHT:
                    ()
                    MainGame.TANK_P1.direction=MainGame.TANK_P1.stop=event.key == pygame.K_UP:
                        ()
                        MainGame.TANK_P1.direction = MainGame.TANK_P1.stop = event.key == pygame.K_DOWN:
                            ()
                            MainGame.TANK_P1.direction = MainGame.TANK_P1.stop = event.key==pygame.K_SPACE:
                    ()


             event.type==pygame.KEYUP:
                    event.key==pygame.K_LEFT event.key==pygame.K_RIGHT \
                        event.key == pygame.K_UP event.key==pygame.K_DOWN:
                     MainGame.TANK_P1.stop=():
    (,left,top):
        .images={
            :pygame.image.load(),
            : pygame.image.load(),
            : pygame.image.load(),
            : pygame.image.load()
        }

        .direction=.image=.images[.direction]
        .rect=.image.get_rect()
        .rect.left=left
        .rect.top=top
        .stop = .speed=():
        .image=.images[.direction]
        MainGame.window.blit(.image,.rect)


():
        .direction==:
            .rect.left>:
                .rect.left-=.speed
        .direction==:
            .rect.left+.rect.width<MainGame.SCREEN_WIDTH:
                .rect.left+=.speed
        .direction==:
            .rect.top > :
                 .rect.top-=.speed
        .direction==:
            .rect.top + .rect.height< MainGame.SCREEN_HEIGHT:
                .rect.top += .speed

    ():
        ():
        ():
        (Tank):
    ():
        ():
        (Tank):

    (,left,top,speed):
        .images={
            :pygame.image.load(),
            :pygame.image.load(),
            :pygame.image.load(),
            :pygame.image.load()
        }
        .direction=.randDirection()
        .image=.images[.direction]
        .rect=.image.get_rect()
        .rect.left=left
        .rect.top=top
        .speed=speed
        .stop=.step=():
            num=random.randint(,)
            num==:
                 num == :
                num == :
                num == :
                ():
        .step<=:
            .direction=.randDirection()
            .step=:
            .move()
            .step-=():
        ():
    ():
        ():
        ():
        ():
        ():
        ():
        ():
    ():
        ():
        ():
    ():
        ():
        ():
    ():
        ():
        __name__==:
    MainGame().startGame()



报错

"C:\Program Files (x86)\Python36-32\python.exe" C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py

pygame 2.0.1 (SDL 2.0.14, Python 3.6.5)

Hello from the pygame community. https://www.pygame.org/contribute.html

Traceback (most recent call last):

  File "C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py", line 284, in <module>

    MainGame().startGame()

  File "C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py", line 28, in startGame

    self.createEnemyTank()

  File "C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py", line 59, in createEnemyTank

    eTank = EnemyTank(left, top, speed)

  File "C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py", line 208, in __init__

    self.image=self.images[self.direction]

KeyError: None


Process finished with exit code 1



老师,帮我看看是什么原因


Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1330楼

pygame,time
random
_display=pygame.display
COLOR_BLACK=pygame.Color(,,)
COLOR_RED=pygame.Color(,,)
():
    window=TANK_P1=SCREEN_HEIGHT=SCREEN_WIDTH=EnemyTank_list=[]
    EnemyTank_count=():
        ():
        _display.init()
        MainGame.window=_display.set_mode([MainGame.SCREEN_WIDTH,MainGame.SCREEN_HEIGHT])
        MainGame.TANK_P1 = Tank(, )
        .createEnemyTank()
        _display.set_caption()

        :
            time.sleep()
            MainGame.window.fill(COLOR_BLACK)
            .getEvent()
            MainGame.window.blit(.getTextface(%),(,))

            MainGame.TANK_P1.displayTank()

            .displayEnemyTank()
            MainGame.TANK_P1.stop == :
                MainGame.TANK_P1.move()
            _display.update()


    ():
        top = i (MainGame.EnemyTank_count):
            left = random.randint(, )
            speed = random.randint(, )
            eTank = EnemyTank(left, top, speed)
            MainGame.EnemyTank_list.append(eTank)


   ():
        eTank MainGame.EnemyTank_list:
            eTank.displayTank()
            eTank.randMove()

    ():
        ()
        ()

    (,text):
        pygame.font.init()
        font=pygame.font.SysFont(,)
        textSurface=font.render(text,,COLOR_RED)
        textSurface

():
        eventList=pygame.event.get()
        event eventList:
    event.type==pygame.QUIT:
                .endGame()
    event.type==pygame.KEYDOWN:
     event.key==pygame.K_LEFT:
                    ()
                    MainGame.TANK_P1.direction=MainGame.TANK_P1.stop=event.key==pygame.K_RIGHT:
                    ()
                    MainGame.TANK_P1.direction=MainGame.TANK_P1.stop=event.key == pygame.K_UP:
                        ()
                        MainGame.TANK_P1.direction = MainGame.TANK_P1.stop = event.key == pygame.K_DOWN:
                            ()
                            MainGame.TANK_P1.direction = MainGame.TANK_P1.stop = event.key==pygame.K_SPACE:
                    ()


             event.type==pygame.KEYUP:
                    event.key==pygame.K_LEFT event.key==pygame.K_RIGHT \
                        event.key == pygame.K_UP event.key==pygame.K_DOWN:
                     MainGame.TANK_P1.stop=():
    (,left,top):
        .images={
            :pygame.image.load(),
            : pygame.image.load(),
            : pygame.image.load(),
            : pygame.image.load()
        }

        .direction=.image=.images[.direction]
        .rect=.image.get_rect()
        .rect.left=left
        .rect.top=top
        .stop = .speed=():
        .image=.images[.direction]
        MainGame.window.blit(.image,.rect)


():
        .direction==:
            .rect.left>:
                .rect.left-=.speed
        .direction==:
            .rect.left+.rect.width<MainGame.SCREEN_WIDTH:
                .rect.left+=.speed
        .direction==:
            .rect.top > :
                 .rect.top-=.speed
        .direction==:
            .rect.top + .rect.height< MainGame.SCREEN_HEIGHT:
                .rect.top += .speed

    ():
        ():
        ():
        (Tank):
    ():
        ():
        (Tank):

    (,left,top,speed):
        .images={
            :pygame.image.load(),
            :pygame.image.load(),
            :pygame.image.load(),
            :pygame.image.load()
        }
        .direction=.randDirection()
        .image=.images[.direction]
        .rect=.image.get_rect()
        .rect.left=left
        .rect.top=top
        .speed=speed
        .stop=.step=():
            num=random.randint(,)
            num==:
                 num == :
                num == :
                num == :
                ():
        .step<=:
            .direction=.randDirection()
            .step=:
            .move()
            .step-=():
        ():
    ():
        ():
        ():
        ():
        ():
        ():
        ():
    ():
        ():
        ():
    ():
        ():
        ():
    ():
        ():
        __name__==:
    MainGame().startGame()


报错
"C:\Program Files (x86)\Python36-32\python.exe" C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py
pygame 2.0.1 (SDL 2.0.14, Python 3.6.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py", line 284, in <module>
    MainGame().startGame()
  File "C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py", line 28, in startGame
    self.createEnemyTank()
  File "C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py", line 59, in createEnemyTank
    eTank = EnemyTank(left, top, speed)
  File "C:/Users/Administrator/Desktop/python课件/坦克游戏/代码/test/tank08.py", line 208, in __init__
    self.image=self.images[self.direction]
KeyError: None

Process finished with exit code 1


Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1331楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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