会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132367个问题

"""新增功能:
   优化我方坦克移动
"""
#导入prcharm模块
import pygame
SCREEN_WIDTH=700    #设置宽度
SCREEN_HEIGHT=500   #设置高度
BG_COLOR=pygame.Color(0,0,0) #设置窗口颜色,0,0,0代表黑色
TEXT_COLOR=pygame.Color(255,0,0)  #设置字体颜色,255,0,0代表红色

#主类
class MainGame():
    window=None
    my_tank=None
    def __init__(self):
        pass
    #开始游戏
    def startGame(self):
        #加载主窗口
        #初始化窗口
        pygame.display.init()
        #设置窗口的大小及显示
        MainGame.window=pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
        #初始化我方坦克
        MainGame.my_tank=Tank(350,250)
        #设置窗口标题
        pygame.display.set_caption("坦克大战1.03")
        while True:
            #给窗口设置填充色
            MainGame.window.fill(BG_COLOR)
            #获取事件
            self.getEvent()
            #绘制文字
            MainGame.window.blit(self.getTextSuface("敌方坦克剩余数量%d"%6),(10,10))
            #调用坦克显示的方法
            MainGame.my_tank.displayTank()
            pygame.display.update()

    #结束游戏
    def endGame(self):
        print("谢谢使用,欢迎再次使用")
        exit()
    #左上角文字的绘制
    def getTextSuface(self,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:
                    #切换方向
                    MainGame.my_tank.dirction="L"
                    MainGame.my_tank.move()
                    print("按下左键,坦克向左移动")
                elif event.key==pygame.K_RIGHT:
                    #切换方向
                    MainGame.my_tank.dirction = "R"
                    MainGame.my_tank.move()
                    print("按下右键,坦克向右移动")
                elif event.key==pygame.K_UP:
                    #切换方向
                    MainGame.my_tank.dirction = "U"
                    MainGame.my_tank.move()
                    print("按下上键,坦克向上移动")
                elif event.key == pygame.K_DOWN:
                    #切换方向
                    MainGame.my_tank.dirction = "D"
                    MainGame.my_tank.move()
                    print("按下下键,坦克向下移动")

#坦克类
class Tank():
    #添加距离左边left 距离上边top
    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.dirction="R"
        #根据当前图片的方向获取图片 surface
        self.image=self.images[self.dirction]
        #根据图片获取区域
        self.rect=self.image.get_rect()
        #设置区域的left 和top
        self.rect.left=left
        self.rect.top=top
        #速度 决定移动的快慢
        self.speed=10



    #移动
    def move(self):
        #判断坦克的方向进行移动
        if self.dirction=="L":
            if self.rect.left>0:
                self.rect.left -= self.speed
        elif self.dirction == "U":
            if self.rect.top>0:
                self.rect.top -= self.speed
        elif self.dirction == "D":
            if self.rect.top+self.rect.height<SCREEN_HEIGHT:
                self.rect.top += self.speed

        elif self.dirction == "R":
            if self.rect.left+self.rect.height<SCREEN_WIDTH:
                self.rect.left += self.speed
    #射击
    def shot(self):
        pass
    #展示坦克方法
    def displayTank(self):
        #获取展示的对象
        self.image=self.images[self.dirction]
        #调用blit方法展示
        MainGame.window.blit(self.image,self.rect)
#我方坦克
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()
    #MainGame().getTextSuface()

老师如何摁着下键让坦克一直移动呀,而不是摁一下移动一下

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

老师我的坦克就只能往上移动,摁下键,左键,右键都是往上运动

"""新增功能:
   1,我方坦克的方向
   2,我方坦克的移动
"""
#导入prcharm模块
import pygame
SCREEN_WIDTH=700    #设置宽度
SCREEN_HEIGHT=500   #设置高度
BG_COLOR=pygame.Color(0,0,0) #设置窗口颜色,0,0,0代表黑色
TEXT_COLOR=pygame.Color(255,0,0)  #设置字体颜色,255,0,0代表红色

#主类
class MainGame():
    window=None
    my_tank=None
    def __init__(self):
        pass
    #开始游戏
    def startGame(self):
        #加载主窗口
        #初始化窗口
        pygame.display.init()
        #设置窗口的大小及显示
        MainGame.window=pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
        #初始化我方坦克
        MainGame.my_tank=Tank(350,250)
        #设置窗口标题
        pygame.display.set_caption("坦克大战1.03")
        while True:
            #给窗口设置填充色
            MainGame.window.fill(BG_COLOR)
            #获取事件
            self.getEvent()
            #绘制文字
            MainGame.window.blit(self.getTextSuface("敌方坦克剩余数量%d"%6),(10,10))
            #调用坦克显示的方法
            MainGame.my_tank.displayTank()
            pygame.display.update()

    #结束游戏
    def endGame(self):
        print("谢谢使用,欢迎再次使用")
        exit()
    #左上角文字的绘制
    def getTextSuface(self,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:
                    #切换方向
                    MainGame.my_tank.direction="L"
                    MainGame.my_tank.move()
                    print("按下左键,坦克向左移动")
                elif event.key==pygame.K_RIGHT:
                    #切换方向
                    MainGame.my_tank.direction = "R"
                    MainGame.my_tank.move()
                    print("按下右键,坦克向右移动")
                elif event.key==pygame.K_UP:
                    #切换方向
                    MainGame.my_tank.direction = "U"
                    MainGame.my_tank.move()
                    print("按下上键,坦克向上移动")
                elif event.key == pygame.K_DOWN:
                    #切换方向
                    MainGame.my_tank.direction = "D"
                    MainGame.my_tank.move()
                    print("按下下键,坦克向下移动")

#坦克类
class Tank():
    #添加距离左边left 距离上边top
    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.dirction="R"
        #根据当前图片的方向获取图片 surface
        self.image=self.images[self.dirction]
        #根据图片获取区域
        self.rect=self.image.get_rect()
        #设置区域的left 和top
        self.rect.left=left
        self.rect.top=top
        #速度 决定移动的快慢
        self.speed=10



    #移动
    def move(self):
        #判断坦克的方向进行移动
        if self.dirction=="L":
            self.rect.left -= self.speed
        elif self.dirction == "U":
            self.rect.top -= self.speed
        elif self.dirction == "D":
            self.rect.top += self.speed
        elif self.dirction == "R":
            self.rect.left += self.speed
    #射击
    def shot(self):
        pass
    #展示坦克方法
    def displayTank(self):
        #获取展示的对象
        self.image=self.images[self.dirction]
        #调用blit方法展示
        MainGame.window.blit(self.image,self.rect)
#我方坦克
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()
    #MainGame().getTextSuface()


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

屏幕截图 2021-08-04 111048.png

这个为什么错误啊

Python 全系列/第二阶段:Python 深入与提高/文件处理 1190楼

# coding=utf-8
from tkinter import *

class Application(Frame):

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


    def createWidget(self):
        self.entry = Entry(self)
        self.entry.grid(row=0,column=0,columnspan=4,pady=10)
        btnText=(
            ('MC','M+','M-','MR'),
            ('C','±','÷','×'),
            (7,8,9,'-'),
            (1,2,3,'='),
            (0 ,'.'),
        )
        for rindex,r in enumerate(btnText):
            for cindex,c in enumerate(r):
                if c== '=':
                    Button(self, text=c, width=2)\
                    .grid(row=rindex+1,column=cindex,rowspan=2,sticky=NSEW)
                if c== 0:
                    Button(self, text=c, width=2)\
                    .grid(row=rindex+1,column=cindex,columnspan=2,sticky=NSEW)
                if c=='.':
                    Button(self, text=c, width=2)\
                    .grid(row=rindex+1,column=cindex+1,sticky=NSEW)
                else:
                    Button(self,text=c,width=2)\
                    .grid(row=rindex+1,column=cindex,sticky=NSEW)


if __name__ == '__main__':
    root = Tk()
    root.geometry('450x300+200+300')
    app = Application(master=root)
    root.mainloop()

image.png,为啥我的0和=变成这样了

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1191楼
Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1193楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1197楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1198楼

问题:txt编码问题,无法正常打开txt。刚开始两次可以,后来加入了文字保存后,再次打开就打不开了;
也尝试了把手动删除txt已添加的文字,结果就一直出现报错。
如何解决?


# coding=gbk
"""开发一个简单的记事本。
  包含:新建、保存、修改文本内容、退出
  包含:各种快捷键的处理
  version 1.0 """

from tkinter import *
from tkinter.filedialog import *  # filedialog 文件对话框
from tkinter.colorchooser import * # colorchooser 颜色选择框
from tkinter.filedialog import *

class Application(Frame):

    def __init__(self, master=None):
        super().__init__(master)  # # super()代表的是父类的定义,而不是父类对象

        self.master = master
        self.textpad = None  # textpad 表示Text文本框对象
        self.pack()
        self.createWidget()

    def createWidget(self):
        # 创建主菜单栏对象
        menubar = Menu(root)

        # 创建子菜单
        menuFile = Menu(menubar)
        menuEdit = Menu(menubar)
        menuHelp = Menu(menubar)

        # 将子菜单加入到主菜单栏
        menubar.add_cascade(label="文件(F)", menu=menuFile)
        menubar.add_cascade(label="编辑(E)", menu=menuEdit)
        menubar.add_cascade(label="帮助(H)", menu=menuHelp)

        # 添加菜单项
        menuFile.add_command(label="新建", accelerator="ctrl+n", command=self.test)
        menuFile.add_command(label="打开", accelerator="ctrl+0", command=self.openfile)
        menuFile.add_command(label="保存", accelerator="ctrl+s", command=self.savefile)

        menuFile.add_separator()  # 添加分割线

        menuFile.add_command(label="退出", accelerator="ctrl+q", command=self.exit)

        # 将主菜单栏加到根窗口
        root["menu"] = menubar

        # 文本编辑区
        self.textpad = Text(root, width=50, height=30)
        self.textpad.pack()

        # 创建快捷菜单(上下文菜单)
        self.contextMenu = Menu(root)
        self.contextMenu.add_command(label="背景颜色", command=self.openAskColor)

        # 为右键绑定事件
        root.bind("<Button-3>", self.createContextMenu)

    def openfile(self):
        self.textpad.delete('1.0', 'end')  # 先把 Text 控件中的内容清空
        with open(askopenfilename(title="opentxt"), encoding="utf-8") as f:  # 打开askopenfilename的固定用法,和编码
            self.textpad.insert(INSERT, f.read())
            self.filename = f.name

    def savefile(self):
        with open(self.filename, "w") as f:
            c = self.textpad.get(1.0, END)
            f.write(c)

    def exit(self):
        root.quit()

    def test(self):
        pass

    def openAskColor(self):
        s1 = askcolor(color="red", title="选择背景色")
        root.config(bg=s1[1])

    def createContextMenu(self, event):
        # 菜单在鼠标右键单击的坐标处显示
        self.contextMenu.post(event.x_root, event.y_root)


if __name__ == '__main__':
    root = Tk()
    root.geometry("450x300+200+300")
    root.title("简易记事本")
    app = Application(master=root)
    root.mainloop()
    
    
    
控制台:
C:\Users\微软\AppData\Local\Programs\Python\Python37\python.exe C:/Users/微软/pycharm_execrise/pythonProject/GUI/note.py
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\微软\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/微软/pycharm_execrise/pythonProject/GUI/note.py", line 62, in openfile
    self.textpad.insert(INSERT, f.read())
  File "C:\Users\微软\AppData\Local\Programs\Python\Python37\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 0: invalid start byte

Process finished with exit code 0

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

代码:

tkinter *
tkinter.filedialog *  tkinter.colorchooser * tkinter.filedialog *

Application(Frame):

    (master=):
        ().(master)  .master = master
        .textpad = .pack()
        .createWidget()

    ():
        menubar = Menu(root)

        menuFile = Menu(menubar)
        menuEdit = Menu(menubar)
        menuHelp = Menu(menubar)

        menubar.add_cascade(==menuFile)
        menubar.add_cascade(==menuEdit)
        menubar.add_cascade(==menuHelp)

        menuFile.add_command(===.test)
        menuFile.add_command(===.openfile)
        menuFile.add_command(===.savefile)

        menuFile.add_separator()  menuFile.add_command(===.exit)

        root[] = menubar

        .textpad = Text(root==)
        .textpad.pack()

        .contextMenu = Menu(root)
        .contextMenu.add_command(==.openAskColor)

        root.bind(.createContextMenu)

    ():
        .textpad.delete()  (askopenfilename(=)=) f:  .textpad.insert(INSERTf.read())
            .filename = f.name

    ():
        (.filename) f:
            c = .textpad.get(END)
            f.write(c)

    ():
        root.quit()

    ():
        ():
        s1 = askcolor(==)
        root.config(=s1[])

    (event):
        .contextMenu.post(event.x_rootevent.y_root)


__name__ == :
    root = Tk()
    root.geometry()
    root.title()
    app = Application(=root)
    root.mainloop()


控制台:

C:\Users\微软\AppData\Local\Programs\Python\Python37\python.exe C:/Users/微软/pycharm_execrise/pythonProject/GUI/note.py

Exception in Tkinter callback

Traceback (most recent call last):

  File "C:\Users\微软\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__

    return self.func(*args)

  File "C:/Users/微软/pycharm_execrise/pythonProject/GUI/note.py", line 62, in openfile

    self.textpad.insert(INSERT, f.read())

  File "C:\Users\微软\AppData\Local\Programs\Python\Python37\lib\codecs.py", line 322, in decode

    (result, consumed) = self._buffer_decode(data, self.errors, final)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 0: invalid start byte


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

课程分类

百战程序员微信公众号

百战程序员微信小程序

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