会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132465个问题
JAVA 全系列/第一阶段:JAVA 快速入门/IDEA的使用和第一个java项目 35086楼

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

class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)    # super代表的是父类的定义,而不是父类的对象
        self.master = master
        self.filename = None   # filename表示打开文本文件的名字
        self.contextMenu = None   # contextMenu表示上下文菜单
        self.textpad = None   # textpad表示文本框对象
        self.pack()
        self.createWidget()

    def createWidget(self):
        # 创建主菜单栏
        menuber = Menu(root)
        # 创建子菜单栏
        menuFlie = Menu(menuber)
        menuEdit = Menu(menuber)
        menuHelp = Menu(menuber)

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

        # 添加菜单选项

        menuFlie.add_command(label="新建", accelerator="ctrl+n", command=self.newfile)
        menuFlie.add_command(label="打开", accelerator="ctrl+o", command=self.openFile)
        menuFlie.add_command(label="保存", accelerator="ctrl+s", command=self.savefile)
        menuFlie.add_separator()  # 添加分割线
        menuFlie.add_command(label="退出", accelerator="ctrl+q", command=self.exit)

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

        # 添加快捷键事件处理
        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=80, height=30)
        self.textpad.pack()

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

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

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

    def openFile(self):
        self.textpad.delete(1.0,END)  # 把控件中的所有内容清空
        with askopenfile(title="打开文本文件") as f:
            self.textpad.insert(INSERT, f.read())
            self.filename = f.name
            #print(f.read())

    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 openAsk(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+300+300")
    root.title("简易记事本")
    app = Application(master=root)
    root.mainloop()

老师我的代码进行新建操作会报错,保存也会报错

image.png

image.png

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

from tkinter.filedialog  import *
from tkinter.colorchooser import *
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.pack()
        self.createWidget()

    def createWidget(self):
        self.drawpad = Canvas(root,width=win_width,height=win_height*0.9,bg=self.bgcolor)
        self.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_line = Button(root,text="直线",name="line")
        btn_line.pack(side="left",padx="10")

        btn_circle = Button(root,text="圆",name="circle")
        btn_circle.pack(side="left",padx="10")

        btn_eraser = Button(root,text="橡皮擦",name="eraser")
        btn_eraser.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_linearrow = Button(root, text="箭头线", name="linearrow")
        btn_linearrow.pack(side="left", padx="10")

        btn_color = Button(root,text="颜色",name="color")
        btn_color.pack(side="left",padx="10")

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

    def myline(self,event):
        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+100")
    root.title("画图软件")
    app = Application(master=root)
    root.mainloop()

老师,这个运行下来不报错也没反应

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

1653290326(1).png

用scrapy框架爬取网易云音乐,返回的response是id=${x.id},而不是<a href="/song?id=1813864802"> 这种样式的,用requests模块是可以获取id的数字的
scrapy settings文件如下:

# Scrapy settings for wangyiyun project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'wangyiyun'

SPIDER_MODULES = ['wangyiyun.spiders']
NEWSPIDER_MODULE = 'wangyiyun.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'wangyiyun (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False
LOG_LEVEL = 'ERROR'

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  # 'Accept-Language': 'en',
}
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36'
DOWNLOAD_DELAY = 2
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'wangyiyun.middlewares.WangyiyunSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'wangyiyun.middlewares.WangyiyunDownloaderMiddleware': 543,
}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
#    'wangyiyun.pipelines.WangyiyunPipeline': 300,
#}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'


Python 全系列/第十五阶段:Python 爬虫开发/scrapy框架使用(旧) 35092楼
JAVA 全系列/第六阶段:项目管理与SSM框架/SpringMVC 35093楼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax案例</title>
    <script src="js/jquery-3.5.1.js"></script>
</head>
<body>
 <span>用户名:</span><input type="text" class="username">
 <span>密码:</span><input type="text" class="password">
 <button class="button">点击</button>
 <script>
     $('button').click(function () {
        $.ajax({
          //请求方式
           type:'post',
          //交互数据格式为JSON
          dataType:'json',
          //指明请求发送到PHP后台的地址
          url:'777.php',
          data:{
               myName:$('.username').val(),
               myPass:$('.password').val()
          },
          success:function (res) {
              if(res.infor==0){
                  alert('登录失败')
              }else {
                  alert('登录成功')
              }
          }
      });

  });
 </script>
</body>
</html>
<?php
  $username=$_post['myName'];
  $password=$_post['myPass'];
  $success=array('msg'=>'ok'),
  if($username=='beixi'&& $password=='123456'){
   $success['infor']=1;
  }else{
   $success['infor']=0;
  }
  echo json_encode($success);
?>

老师麻烦看一下前后端没法交互  谢谢老师

WEB前端全系列/第五阶段:前后端交互/PHP、数据库编程与设计 35095楼
JAVA 全系列/第五阶段:JavaWeb开发/Servlet技术详解 35096楼

package com.xhcxy;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 发送消息的线程Send1
 */
class Send1 extends Thread{
    private Socket socket;
    private Scanner scanner;
    public Send1(Socket socket,Scanner scanner){
        this.socket = socket;
        this.scanner = scanner;
    }
    @Override
    public void run() {
        this.send1Mgs();
    }
    public void send1Mgs(){
        Scanner scanner = null;
        PrintWriter pw = null;
        try {
            scanner = new Scanner(System.in);
            pw = new PrintWriter(this.socket.getOutputStream());
            while (true){
                String mgs = scanner.nextLine();
                pw.println(mgs);
                pw.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (scanner !=null){
                scanner.close();
            }
            if (pw != null){
                pw.close();
            }
            if (this.socket != null){
                try {
                    this.socket .close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
/**
 * 接收消息的线程Receive1
 */
class Receive1 extends Thread{
    private Socket socket;
    public Receive1(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        super.run();
    }
    public void receive1Mgs(){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            while (true){
                String mgs = br.readLine();
                System.out.println("他说:"+mgs);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (this.socket != null){
                try {
                    this.socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class GoodTcp {
    public static void main(String[] args) {
        Scanner scanner = null;
        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            scanner = new Scanner(System.in);
            System.out.println("请输入:server,<port>或者:<ip>,<port>");
            String str = scanner.nextLine();
            String[] arr = str.split(",");
            if ("server".equals(arr[0])){
                System.out.println("TCP Server Listen at"+arr[1]+"......");
                serverSocket = new ServerSocket(Integer.parseInt(arr[1]));
                serverSocket.accept();
                System.out.println("连接成功!!");
            }else {
                socket = new Socket(arr[0],Integer.parseInt(arr[1]));
                System.out.println("连接成功!!");
            }
            new Send1(socket,scanner).start();
            new Reaceice(socket).start();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

为什么会链接成功报错,老师image.png

JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 35097楼
Python 全系列/第八阶段:Vue框架/vue框架 35098楼
JAVA 全系列/第十二阶段:消息中间件(异步消息传递)/ActiveMQ 35099楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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