会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132989个问题
Python 全系列/第一阶段:Python入门/控制语句 22666楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 22667楼
Python 全系列/第一阶段:Python入门/控制语句 22668楼
JAVA 全系列/第六阶段:项目管理与SSM框架/Mybatis 22669楼
Python 全系列/第九阶段:Flask百战电商后台系统/Flask百战电商后台项目 22670楼

"""开发记事本软件菜单"""


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

class Application(Frame):
    def __init__(self,master=None):
        super().__init__(master)
        self.master=master
        self.textpad=None
        self.pack()
        self.createWidget()
    def createWidget(self):
        #创建主菜单栏
        menubar=Menu(root)

        #print(menubar)
        #创建子菜单
        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.newfile)
        menuFile.add_command(label="打开",accelerator="<Ctrl-o>",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.config(menu=menubar)
        root["menu"]= menubar


        #添加文本框
        self.textpad=Text(root)
        self.textpad.pack()

        #创建上下菜单
        self.contextMenu=Menu(root)
        self.contextMenu.add_command(label="背景颜色",command=self.openAskColor)
        #鼠标右键绑定事件
        root.bind("<Button-3>",self.createContextMenu)#通过鼠标右键单击组件而弹出的菜单,需要通过调用post显示鼠标的坐标来显示位置,还有定义方法显示

    def newfile(self):
        self.textpad.delete("1.0","end")
        self.filename=asksaveasfile(title="另存为",initialfile="未命名.txt",filetypes=[("文本文档","*.txt")],
                                    defaultextension=".txt")

        self.savefile()

    def openfile(self):
        self.textpad.delete("1.0","end")#把text控件中的所有内容情空
        with askopenfile(title="打开文本文件") as f:
            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)#获取textpad内的所有内容,
            f.write(c)#写到打开的文件中

    def exit(self):
        root.quit()

    def openAskColor(self):
        s1=askcolor(color="red",title="选择背景色")
        self.textpad.config(bg=s1[1])
    def createContextMenu(self,event):
        #菜单在鼠标右键单击的坐标处显示
        self.contextMenu.post(event.x_root,event.y_root)




if __name__ == '__main__':
    root=Tk()
    root.geometry("400x300+200+300")
    root.title("百战程序员简单的记事本")
    app=Application(master=root)
    root.mainloop()

点击newfile保存后报错是这个,不知道哪里出问题

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/Test/Desktop/study/my26.py", line 54, in newfile
    self.savefile()
  File "C:/Users/Test/Desktop/study/my26.py", line 65, in savefile
    with open(self.filename,"w") as f:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

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

老师,我在用post 方法的时候,后台接收数据总是出现时有时没有的情况。然后报这个错误

1618134804(1).png

这时我写php文件先写这个

print_r($_POST);php 结尾处 print_r($success); 后台才会接收到前台数据;并且返回信息,否则连后台信息也不会返回。
若这个print_r($success)不写,也不行。
1618134898(1).png
1618135088(1).png
<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>jqajax</title>
</head>
<style>

</style>
<body>
<div>
    用户名:<input type="text" name="usename" class="usename"><br/>
    密码:<input type="text" name="pass" class="pass"><br/>
    <button>提交</button>
</div>
<script>
    //获取类
    var usename=document.querySelector('.usename');
    var password=document.querySelector('.pass');
    var btn=document.querySelector('button');
    //提交时
    btn.onclick=function () {
        //创建一个xhr对象 准备发送ajax请求
        //考虑兼容性问题
        // if(window.XMLHttpRequest){
        //     var xhr=new XMLHttpRequest();
        // }else if(window.ActiveXObject){
        //     var xhr=new ActiveXObject();
        // }
        var xhr=new XMLHttpRequest();
        //目的:用onreadystatechange监听后台是否收到前台数据的回调函数
        xhr.onreadystatechange=function () {
            //判断前台向后台发送请求的状态 值为0 1 2 3 4
            if(xhr.readyState==4){
                //判断前端是否准备收到后台反馈得数
                if(xhr.status==200) {
                    //获取后台传送的数据
                    console.log(xhr.responseText)
                    //解析数据
                    // console.log(JSON.parse(xhr.responseText))
                }
            }
        }
        // //get 方法
        // //当准备好接收后台数据的回调函数后,着手准备发送ajax请求
        // xhr.open('get','ajax.php?name='+usename.value+'&pass='+password.value,true);
        // //设置后通过send方法发送到后台post
        // xhr.send(null);
        //post 方法
        // //当准备好接收后台数据的回调函数后,着手准备发送ajax请求
        xhr.open('post','ajax.php',true);
        //设置后通过send方法发送到后台
        var data=new FormData();
        data.append('name',usename.value);
        data.append('pass',password.value);
        xhr.send(data);
    }
</script>
</body>
</html>
//获取前台数据
//print_r($_POST);
$name=$_POST['name'];
$pass=$_POST['pass'];
$success=array('msg'=>'ok');
 //连接数据库
   $con = mysqli_connect('localhost','root','','ceshi');
   if($con){
       mysqli_query($con,"set names utf8");
       mysqli_query($con,"set character_set_client=utf8");
       mysqli_query($con,"set character_set_results=utf8");
        $sql='select * from `usename` where 1 ';
         $res=$con->query($sql);
         if($res->num_rows>0){
         $info=[];
         for($i=0;$row=$res->fetch_assoc();$i++){
         $info[$i]=$row;
         }
         }
         //判断是否登录成功
         $flag=false;
         for($j=0;$j<count($info);$j++){
         if($info[$j]['name']==$name){
         if($info[$j]['pass']==$pass){
                   $success['info']=0;
                   $flag=true;
                   break;
                  }
         }else{
          $success['info']=1;
         }
         }
         }
 else {
          $success['info']=2;
      }
       json_encode($success);
       print_r($success);
  ?>


WEB前端全系列/第六阶段:Http服务与Ajax模块(旧)/Http服务与Ajax编程 22672楼

老师,为什么我找着视频中的源码敲了一遍然后,保存所写的文本时总是报错。。





"""开发记事本软件的菜单

"""

coding=utf-8


from tkinter.filedialog import *

from tkinter.colorchooser import *

from tkinter import *




class Application(Frame):


    def __init__(selfmaster=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.newfile)

        menuFile.add_command(label="打开"accelerator="ctrl+o"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


        # 增加快捷键的处理

        root.bind("<Control-n>",lambda event:self.newfile())

        root.bind("<Control-o>",lambda event:self.openfile())

        root.bind("<Control-s>",lambda event:self.savefile())

        root.bind("<Control-q>",lambda event:self.exit())


        #文本编辑区

        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 newfile(self):

        self.textpad.delete("1.0""end")  # 把text控件中所有的内容清空

        self.filename= asksaveasfilename(title="另存为",initialfile="未命名.txt",

                          filetypes=[("文本文档","*.txt")],

                          defaultextension=".txt")

        self.savefile()


    def openfile(self):

        self.textpad.delete("1.0","end")        # 把text控件中所有的内容清空

        with askopenfile(title="打开文本文件"as f:

            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 openAskColor(self):

        s1 = askcolor(color="red",title="选择背景色")

        self.textpad.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()

截图如下:

屏幕截图 2021-04-11 173723.png

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

老师你好,我跟着高老师的源码敲了一遍,然后保存文件的时候总是报错,是怎么回事

"""开发记事本软件的菜单
"""
coding=utf-8

from tkinter.filedialog import *
from tkinter.colorchooser import *
from tkinter 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.newfile)
        menuFile.add_command(label="打开", accelerator="ctrl+o", 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

        # 增加快捷键的处理
        root.bind("<Control-n>",lambda event:self.newfile())
        root.bind("<Control-o>",lambda event:self.openfile())
        root.bind("<Control-s>",lambda event:self.savefile())
        root.bind("<Control-q>",lambda event:self.exit())

        #文本编辑区
        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 newfile(self):
        self.textpad.delete("1.0", "end")  # 把text控件中所有的内容清空
        self.filename= asksaveasfilename(title="另存为",initialfile="未命名.txt",
                          filetypes=[("文本文档","*.txt")],
                          defaultextension=".txt")
        self.savefile()

    def openfile(self):
        self.textpad.delete("1.0","end")        # 把text控件中所有的内容清空
        with askopenfile(title="打开文本文件") as f:
            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 openAskColor(self):
        s1 = askcolor(color="red",title="选择背景色")
        self.textpad.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()

报错截图:

在面板上打字然后保存就会报错

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 22675楼
Python 全系列/第三阶段:Python 网络与并发编程/并发编程 22680楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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