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

问题: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编程(隐藏) 18961楼

代码:

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编程(隐藏) 18962楼
Python 全系列/第一阶段:AI驱动的Python编程/面向对象 18964楼
JAVA 全系列/第一阶段:AI驱动的JAVA编程/IDEA的使用和第一个java项目 18965楼
JAVA 全系列/第十一阶段:智能家居项目(旧)/至尊智能家居第一天 18966楼
JAVA 全系列/第六阶段:项目管理与SSM框架/Mybatis 18970楼
WEB前端全系列/第一阶段:HTML5+CSS3模块/前端入门与基础知识 18972楼
JAVA 全系列/第一阶段:AI驱动的JAVA编程/控制语句、方法、递归算法 18974楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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