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

老师出现以下报错:查看了一些解决方法,说可以在open文件时加encoding=gbk,但是askopenfile的参数中没有编码这个参数,请问怎么解决

UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 8: illegal multibyte sequence

#coding=cp936
from tkinter import *
from tkinter.filedialog import *
from tkinter.colorchooser import *


class Application(Frame):
    def __init__(self, master=None):
        super(Application, self).__init__(master)
        self.master = master
        self.filename = None
        self.nt = None
        self.pack()
        self.notebook()

    def notebook(self):
        self.nt = Text(self.master, width=100, height=30, font=("黑体", 20))
        self.nt.pack()
        mainmenu = Menu(self.master)
        menu1 = Menu(mainmenu, tearoff=0)
        menu2 = Menu(mainmenu, tearoff=0)
        menu3 = Menu(mainmenu, tearoff=0)
        menu4 = Menu(mainmenu, tearoff=0)
        self.master["menu"] = mainmenu
        mainmenu.add_cascade(label="文件", menu=menu1)
        mainmenu.add_cascade(label="编辑", menu=menu2)
        mainmenu.add_cascade(label="工具", menu=menu3)
        mainmenu.add_cascade(label="帮助", menu=menu4)

        menu1.add_command(label="新建", accelerator="ctrl+n", command=self.newfile)
        menu1.add_command(label="打开", accelerator="ctrl+o", command=self.openfile)
        menu1.add_command(label="保存", accelerator="ctrl+s", command=self.savefile)
        menu1.add_separator()
        menu1.add_command(label="退出", accelerator="ctrl+q", command=self.quit)
        menu3.add_command(label="颜色选择", command=self.opencolor)

    def newfile(self):
        pass

    def openfile(self):
        with askopenfile(title="打开文件", initialdir="D:/", filetypes=[("文本文档", ".txt")]) as f:
            self.nt.insert(INSERT, f.read())
            self.filename = f.name
            print(self.filename)
            print(f)

    def savefile(self):
        pass

    def quit(self):
        self.master.quit()

    def opencolor(self):
        pass


if __name__ == '__main__':
    root = Tk()
    root.title("测试菜单")
    # root.geometry("200x200+200+200")
    Application(master=root)
    root.mainloop()

image.png

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

'''
新增方法:
 加载主窗口

'''
#导入pygame模块
import pygame
# #pygame官方网站:www.pygame.org
SCREEN_WIDTH=700
SCREEN_HEIGHT=500
class MianGame():
#主类
    window=None
    def __init__(self):
        pass
#开始游戏

    def Startgame(self):
        pass
        #加载主窗口
        pygame.display.init()
        MianGame.window=pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
#结束游戏

    def Endgame(self):
        pass
class Tank():
    #坦克类
    def __init__(self):
        pass
    #移动
    def move(self):
        pass
    #射击
    def shoot(self):
        pass
    #展示坦克的方法
    def displayTank(self):
        pass

    #我方坦克类,继承的是坦克类
class MyTank(Tank):
    def __init__(self):
        pass

    #敌方坦克
class EnemyTank(Tank):
    def __init__(self):
        pass

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

    #墙壁类
class wall():
    def __init__(self):
        pass
    #展示墙壁的方法
    def displaywall(self):
        pass

    #爆炸类
class Explode():
    def __init__(self):
        pass
    #展示爆炸效果的方法
    def displayExlpode(self):
        pass
    #音效类
class Music():
    def __init__(self):
        pass
    #展示音效的方法
    def displayMusic(self):
        pass
if '_name_'=='_main_':
    MianGame().Startgame()

老师,我的窗口加载不出来,没有报错

blob.png

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

image.png

老师,我不知道我这里为什么直线画不出来

from tkinter.filedialog import *
from tkinter.colorchooser import *
from tkinter.filedialog import *

# 安装pyinstaller方法 file----setting----project----project interpretor

win_width = 900
win_height = 450


class Application(Frame):
    def __init__(self, master=None, bgcolor='#000000'):
        super().__init__(master)
        self.master = master
        self.bgcolor = bgcolor
        self.x = 0
        self.y = 0
        self.fgcolor = '##ff0000'
        self.lastdraw = 0                       # 表示最后绘制图形的id
        self.startDrawFlag = False
        self.pack()
        self.createWidget()

    def createWidget(self):
        # 创建绘图面板
        drawpad = Canvas(root, width=win_width, height=win_height * 0.9, bg=self.bgcolor)
        drawpad.pack()

        # 创建按钮
        btn_start = Button(root, text='开始', name='start')
        btn_start.pack(side='left', padx='10')
        btn_pen = Button(root, text='画笔', name='pen')
        btn_pen.pack(side='left', padx='10')
        btn_rect = Button(root, text='矩形', name='rect')
        btn_rect.pack(side='left', padx='10')
        btn_clear = Button(root, text='清除', name='clear')
        btn_clear.pack(side='left', padx='10')
        btn_erasor = Button(root, text='橡皮', name='erasor')
        btn_erasor.pack(side='left', padx='10')
        btn_line = Button(root, text='直线', name='line')
        btn_line.pack(side='left', padx='10')
        btn_lineArror = Button(root, text='箭头', name='lineArror')
        btn_lineArror.pack(side='left', padx='10')
        btn_color = Button(root, text='颜色', name='color')
        btn_color.pack(side='left', padx='10')

        # 事件处理
        btn_pen.bind_class('Button', '<1>', self.eventManager)
        self.drawpad.bind('<ButtonRelease-1>',self.stopdraw)

    def eventManager(self,event):
        name = event.widget.winfo_name()
        print(name)
        if name == 'line':
            self.drawpad.bind('<B1-Motion>', self.myline)

    def stopdraw(self,event):
        self.startDrawFlag = False

    def myline(self,event):
        self.drawpad.delete(self.lastdraw)
        self.lastdraw = 0

        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y

        self.lastdraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)


if __name__ == '__main__':
    root = Tk()
    root.geometry(str(win_width)+'x'+str(win_height)+'+200+300')
    root.title('一个经典的GUI程序类测试')
    app = Application(master=root)
    root.mainloop()


Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2630楼
Python 全系列/第二阶段:Python 深入与提高/(旧)坦克大战 2631楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 2632楼
Python 全系列/第二阶段:Python 深入与提高/坦克大战 2634楼

from tkinter import *  # 引用tkinter模块
from tkinter.filedialog import *  # 引用对话框
from tkinter.colorchooser import *  # 引用颜色选择器

win_width = 900
win_height = 500


class Application(Frame):
    def __init__(self, master=None, bgcolor="#000000"):
        super().__init__(master)
        self.master = master
        self.bgcolor = bgcolor
        self.fgcolor = "#ff0000"
        self.x = 0
        self.y = 0
        self.lastDraw = 0  # 表示最后绘制的图形的 id
        self.startDrawFlag = False
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.drawpad = Canvas(root, width=win_width, height=win_height * 0.9, bg=self.bgcolor)
        self.drawpad.pack()

        btn_pen = Button(root, text="画笔", name="pen")
        btn_pen.pack(side="left", padx="10")
        btn_line = Button(root, text="直线", name="line")
        btn_line.pack(side="left", padx="10")

        btn_pen.bind_class("Button", "<1>", self.eventManager)
        self.drawpad.bind(("<ButtonRelease-1>", self.stopDraw))

    def eventManager(self, event):
        name = event.widget.winfo_name()
        print(name)
        if name == "line":
            self.drawpad.bind("<B1-Motion>", self.myline)

    def stopDraw(self, event):
        self.startDrawFlag = False
        self.lastDraw = 0

    def myline(self, event):

        self.drawpad.delete(self.lastDraw)
        
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y

        self.lastDraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)


if __name__ == '__main__':
    root = Tk()
    root.title("酥酥的画架")
    root.geometry(str(win_width) + "x" + str(win_height) + "+200+100")
    app = Application(master=root)
    root.mainloop()

111.png老师麻烦帮我看一下,卡在“释放鼠标后构建新的直线”这一步上。stopDraw代码没找到有什么问题,但结论效果出不来


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

我方坦克时,游戏界面停止了,并没有出现爆炸效果!


pygametimerandom
pygame.sprite Sprite

SCREEN_WIDTH SCREEN_HEIGHT BG_COLOR pygame.TEXT_COLOR pygame.BaseItemSpritepygame.sprite.Sprite.MainGamewindow my_tank enemyTankList enemyTankCount myBulletList enemyBulletList explodeList pygame.display.MainGame.window pygame.display.SCREEN_WIDTHSCREEN_HEIGHTMainGame.my_tank Tank.pygame.display.time.MainGame.window.BG_COLOR.MainGame.window..MainGame.enemyTankListMainGame.my_tank MainGame.my_tank.liveMainGame.my_tank.MainGame.my_tank
                MainGame.my_tank ....MainGame.my_tank MainGame.my_tank.liveMainGame.my_tank.stopMainGame.my_tank.pygame.display.top i MainGame.enemyTankCountleft random.speed random.enemy EnemyTanklefttopspeedMainGame.enemyTankList.enemyexplode MainGame.explodeListexplode.liveexplode.MainGame.explodeList.explodeenemyTank MainGame.enemyTankListenemyTank.liveenemyTank.enemyTank.enemyBullet enemyTank.enemyBulletMainGame.enemyBulletList.enemyBulletMainGame.enemyTankList.enemyTankmyBullet MainGame.myBulletListmyBullet.livemyBullet.myBullet.myBullet.MainGame.myBulletList.myBulletenemyBullet MainGame.enemyBulletListenemyBullet.liveenemyBullet.enemyBullet.enemyBullet.MainGame.enemyBulletList.enemyBulletpygame.font.font pygame.font.textSurface font.TEXT_COLORtextSurface

    eventList pygame.event.event eventListevent.type pygame.QUIT.event.type pygame.KEYDOWNMainGame.my_tank MainGame.my_tank.liveevent.key pygame.K_LEFTMainGame.my_tank.direction MainGame.my_tank.stop event.key pygame.K_RIGHTMainGame.my_tank.direction MainGame.my_tank.stop event.key pygame.K_UPMainGame.my_tank.direction MainGame.my_tank.stop event.key pygame.K_DOWNMainGame.my_tank.direction MainGame.my_tank.stop event.key pygame.K_SPACEMainGame.myBulletListmyBullet BulletMainGame.my_tankMainGame.myBulletList.myBulletevent.type pygame.KEYUPevent.key pygame.K_UP pygame.K_DOWN event.key pygame.K_LEFT event.key pygame.K_RIGHTMainGame.my_tank MainGame.my_tank.liveMainGame.my_tank.stop TankBaseItem.images pygame.image.pygame.image.pygame.image.pygame.image..direction .image .images.direction.rect .image..rect.left .rect.top .speed .stop .live .direction .rect.left .rect.left .speed
        .direction .rect.top .rect.top .speed
        .direction .rect.top .rect.height SCREEN_HEIGHT.rect.top .speed
        .direction .rect.left .rect.height SCREEN_WIDTH.rect.left .speed

    Bullet.image .images.directionMainGame.window..image.rectMyTankTankEnemyTankTankEnemyTank..images pygame.image.pygame.image.pygame.image.pygame.image..direction ..image .images.direction.rect .image..rect.left .rect.top .speed .flag .step num random.num num num num .step .direction ..step ..step num random.num BulletBulletBaseItem.image pygame.image..direction .direction
        .rect .image..direction .rect.left .rect.left .rect.width.rect.width.rect.top .rect.top .rect.height
        .direction .rect.left .rect.left .rect.width.rect.width.rect.top .rect.top .rect.height
        .direction .rect.left .rect.left .rect.width.rect.width.rect.top .rect.top .rect.width.rect.width.direction .rect.left .rect.left .rect.width
            .rect.top .rect.top .rect.width.rect.width.speed .live .direction .rect.top .rect.top .speed
            .live .direction .rect.left .rect.width SCREEN_WIDTH.rect.left .speed
            .live .direction .rect.top .rect.height SCREEN_HEIGHT.rect.top .speed
            .live .direction .rect.left .rect.left .speed
            .live MainGame.window..image.rectenemyTank MainGame.enemyTankListpygame.sprite.enemyTankenemyTank.live .live explode ExplodeenemyTankMainGame.explodeList.explodeMainGame.my_tank MainGame.my_tank.livepygame.sprite.MainGame.my_tankexplode ExplodeMainGame.my_tankMainGame.explodeList.explode.live MainGame.my_tank.live WallExplode.rect .rect
        .images pygame.image.pygame.image.pygame.image.pygame.image.pygame.image..step .image .images.step.live .step .images.image .images.step.step MainGame.window..image.rect.live .step Music__name__ MainGame.

11.jpg

22.jpg

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

# 编程计算水费
import plotly as py
from plotly import figure_factory as FF
import plotly.graph_objs as pygo
import pandas as pd
import numpy as np
import csv

# 写一个txt文件
f1 = open(r"water.txt","w",encoding="utf-8")
data = "账号 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月\n\
0000359333 772 789 806 847 880 901 950 991 1022 1043 1064 1089 1114\n\
0000359305 121 132 145 156 168 179 192 206 219 230 246 258 273\n\
0000359708 1008 1046 1102 1167 1209 1255 1311 1362 1407 1453 1512 1563 1604\n\
0000359504 541 567 590 622 651 689 701 732 758 775 796 814 847\n\
0000359209 401 412 441 466 479 490 508 522 541 572 603 637 666"
f1.write(data)

# 计算txt文件数据
f2=open("water.txt","r")
head=f2.readline()
sum=0
for line in f2.readlines():
    l=line.split()
    for i in range(len(l)/2):
        s=int(l[i*2+1])+int(l[i*2+2])*1.05
        sum+=s
print(sum)

# 将txt文件转为csv文件
data_txt = np.loadtxt('water.txt')
data_txtDF = pd.DataFrame(data_txt)
data_txtDF.to_csv('water.csv',index=False)

#绘制折线图
pyplt = py.offline.plot     #离线模式
data = pd.read_csv("water.csv",encoding="GBK")
table = FF.create_table(data)
data["水费"]=sum
xdata = data["账号"].tolist()   # 取账户这一列,做列表
ydata = data["水费"].tolist()     # 取水费这一列,做列表
trace = pygo.Scatter(x=xdata,y=ydata,name="水费")     # 水费折线
money = pygo.data(trace)
layout = pygo.Layout(title="用户一年的水费")       #图的标题
money= pygo.Figure(data=money,layout=layout)
print(money)

#关闭文件
f1.close()
f2.close()

创建水量文件“water.txt”文件,其内容第一列为账号,后面是每个月的用水量(后一个数-前一个数),共十二个月。每立方米需付1.05元。 编程计算每户一年的水费,并画出折线图。

0000359333 772  789 806 847 880 901 950 991 1022 1043 1064 1089 1114

0000359305 121  132 145 156 168 179 192 206 219 230 246 258 273

0000359708 1008 1046 1102 1167 1209 1255 1311 1362 1407 1453 1512 1563 1604

0000359504 541 567 590 622 651 689 701 732 758 775 796 814 847

0000359209 401 412 441 466 479 490 508 522 541 572 603 637 666。


老师,这道题我是先写一个txt文件,然后计算txt文件中的数据,后转成表格形式的csv文件,再用csv文件绘制折线图。因为这是昨天晚上写的,那个时候提问老师也下班了,而且掌握的不熟练,程序不长所以我就没有写一下运行一下。报的错误为:


txt文件可以正常输出,但txt文件计算数据时为0,接下来的步骤全是按照平常课程老师举的例子来写的。麻烦老师花点时间看看题目教教我,求教,谢谢!


Python 全系列/第二阶段:Python 深入与提高/文件处理 2639楼
Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 2640楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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