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

老师,运行出现这个错误,该怎么解决呢error.PNG

#coding=utf-8
import pygame,time,random
SCREEN_WIDTH=600
SCREEN_HEIGHT=500
BG_COLOR=pygame.Color(0,0,0)
TEXT_COLOR=pygame.Color(255,0,0)
class MainGame():
    window = None
    my_tank = None
    enemyTankList = []
    enemyTankCount = 5
    def __init__(self):
        pass


    def startGame(self):
        pygame.display.init()
        MainGame.my_tank=Tank(300,250)
        self.creatEnemyTank()
        MainGame.window=pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT),0,32)
        pygame.display.set_caption("坦克大战")
        while True:
            time.sleep(0.02)
            MainGame.window.fill(BG_COLOR)
            self.getEvent()
            MainGame.window.blit(self.getTextSurface("敌方坦克剩余数量%d"%6),(10,10))
            MainGame.my_tank.displayTank()
            self.blitEnemyTank()
            if not MainGame.my_tank.stop:
                MainGame.my_tank.move()
            pygame.display.update()

    def creatEnemyTank(self):
        top=100
        for i in range(MainGame.enemyTankCount):
            left=random.randint(0,600)
            speed=random.randint(1,4)
            enemy=EnemyTank(left,top,speed)
            MainGame.enemyTankList.append(enemy)
    def blitEnemyTank(self):
        for enemyTank in MainGame.enemyTankList:
            enemyTank.displayTank()



    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.stop=False
                    #print("按下左键,坦克向左移动")
                elif event.key==pygame.K_RIGHT:
                    MainGame.my_tank.direction = "R"
                    MainGame.my_tank.stop = False
                    #print("按下右键,坦克向右移动")
                elif event.key==pygame.K_UP:
                    MainGame.my_tank.direction = "U"
                    MainGame.my_tank.stop = False
                    #print("按下上键,坦克向上移动")
                elif event.key==pygame.K_DOWN:
                    MainGame.my_tank.direction = "D"
                    MainGame.my_tank.stop = False
                    #print("按下下键,坦克向下移动")
                elif event.key == pygame.K_SPACE:
                    pass
                    #print("发射子弹")
            if event.type == pygame.KEYUP:
                if event.key==pygame.K_DOWN or event.key==pygame.K_UP or event.key==pygame.K_RIGHT or event.key==pygame.K_RIGHT:
                    MainGame.my_tank.stop=True


    def endGame(self):
        print("谢谢使用,欢迎再次使用")
        exit()

    def getTextSurface(self,text):
        pygame.font.init()
        font=pygame.font.SysFont("kaiti",18)
        textSurface=font.render(text,True,TEXT_COLOR)
        return textSurface

class Tank():
    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.direction="U"
        self.image=self.images[self.direction]
        self.rect=self.image.get_rect()
        self.rect.left=left
        self.rect.top=top
        self.speed=5
        self.flag=True



    def randDirection(self):
        num=random.randint(1,4)
        if num==1:
            return "U"
        elif num==2:
            return "D"
        elif num==3:
            return "L"
        elif num==4:
            return "R"
    def move(self):
        if   self.direction=="L":
            if self.rect.left>0:
                self.rect.left-=self.speed
        elif self.direction=="R":
            if self.rect.left+self.rect.height <SCREEN_WIDTH:
                self.rect.left+=self.speed
        elif self.direction == "U":
            if self.rect.top > 0:
                self.rect.top -= self.speed
        elif self.direction == "D":
            if self.rect.top + self.rect.height < SCREEN_HEIGHT:
                self.rect.top += self.speed
    def displayTank(self):
        self.image = self.images[self.direction]
        MainGame.window.blit(self.image,self.rect)
class EnemyTank(Tank):
    def __init__(self,left,top,speed):
        self.images={
            'U':pygame.image.load('img/enemy1U.gif'),
            'D':pygame.image.load('img/enemy1D.gif'),
            'L':pygame.image.load('img/enemy1L.gif'),
            'R':pygame.image.load('img/enemy1R.gif')
        }

        self.direction=self.randDirection()
        self.image=self.images[self.direction]
        self.rect=self.image.get_rect()
        self.rect.left=left
        self.rect.top=top
        self.speed=speed
        self.flag=True

if __name__=="__main__":
    MainGame().startGame()


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


我照着敲的,访问时候弹出这个

image.png

package com.security.handle;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author  liufupeng
 * @date  2021/5/11
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {

        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.setContentType("application/json:charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.println("{\"code\":\"403\",\"msg\":\"无权限\"}");
        writer.flush();
        writer.close();
    }


}
package com.security.config;

import com.security.handle.MyAccessDeniedHandler;
import com.security.handle.MyAuthenticationFailHandler;
import com.security.handle.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author liufupeng
 * @date 2021/5/8
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 表单认证
        http.formLogin()
                .loginProcessingUrl("/login") // 当发现/login时认为是登陆,需要执行UserDetailsServiceImpl
//                .successForwardUrl("/toMain") // 登陆成功 此处为post请求
//                .failureForwardUrl("/fail")
                .usernameParameter("username") //自定义username字段
                .passwordParameter("password")
                .successHandler(new MyAuthenticationSuccessHandler("/toMain"))
                .failureHandler(new MyAuthenticationFailHandler("/fail.html"))
                .loginPage("/login.html");

        //  url 拦截
        http.authorizeRequests()
                .antMatchers("/login.html", "/fail.html").permitAll() // 登陆不需要被认证
//                .antMatchers("/main1.html").hasAuthority("admin")
                .antMatchers("/main1.html").hasIpAddress("127.0.0.1")
                .anyRequest().authenticated();

        http.csrf().disable();

        http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler);
    }

    @Bean
    public PasswordEncoder getPe() {
        return new BCryptPasswordEncoder();
    }
}


JAVA 全系列/第十阶段:权限控制与安全认证/Spring Security(旧) 21694楼
Python 全系列/第一阶段:Python入门/面向对象 21696楼
JAVA 全系列/第六阶段:JavaWeb开发/Web实战案例 21697楼

老师你好,34行的wait()语句他可以自己单独调用的吗,还是跟23行里面的sleep(6)有关联的,程序开始运行的时候调用了ti,t2线程打印 车开走了和等车 这2句话,一起等待了6秒之后才变为True,有点没搞懂

from threading import Thread
from threading import Event
from time import sleep
'''
1.Event()可以创建一个事件管理标志,该标志(event)默认为False。
2.event.wait(timeout=None):调用该方法的线程会被阻塞,如果设置了,
  timeout 参数,超时后,线程会停止阻塞继续执行;
'''
def car():
    #global count
    num=0
    while True:
        if even.is_set(): #判断event的标值是否为True
            print('车已经到站,可以上车')
            sleep(1)
            #count=count+1
            num=num+1
            if num % 5  == 0:
                even.clear() #将event设置为False

        else:
            print('车开走了...')
            sleep(6)
            #count=1
            even.set()  #将event设置为True

def person():
    while True:
        if even.is_set():
            print('上车')
            sleep(1)
        else:
            print('等车')
            even.wait()
            #sleep(1)

if __name__=='__main__':
    even=Event()
    #count=1
    t1=Thread(target=car)
    t2=Thread(target=person)
    t1.start()
    t2.start()


Python 全系列/第三阶段:Python 网络与并发编程/并发编程 21698楼
人工智能/第十阶段:机器学习-Kaggle竞赛实战/网页分类案例 21699楼
Python 全系列/第一阶段:Python入门/面向对象 21700楼

#测试grid布局管理器
from tkinter import *

class Application(Frame):

    def __init__(self,master=None):  #master默认是None,实例化时传入参数root替换None
        super().__init__(master)
        self.master=master
        self.pack()
        self.createWidget()

    def createWidget(self):   #定义框内容以及属性

        self.l0=Label(self,text="用户名")
        #grid(row=0,column=0)--在0行0列放置
        self.l0.grid(row=0,column=0)

        #self.v=StringVar()
        #self.e0 = Entry(self, textvariable=self.v)
        #self.e0.grid(row=0, column=1)
        Entry(self).grid(row=0, column=1)

        self.l1 = Label(self, text="密码").grid(row=1, column=0)

        #self.v1 = StringVar()
        #self.e1 = Entry(self, textvariable=self.v1,show='*')
        #self.e1.grid(row=1, column=1)
        Entry(self,show='*').grid(row=1, column=1)

        self.l2 = Label(self, text="用户名为手机号").grid(row=0, column=2)

        Button(self,text="登录").grid(row=2, column=1,sticky=EW)  #EW,沿东西方向都有
        Button(self, text="取消").grid(row=2, column=2, sticky=E)


if __name__=="__main__":
    root=Tk()                        #创建框大小、位置以及标题
    app=Application(master=root)
    root.title("grid")
    root.geometry("400x120+450+200")
    root.mainloop()

老师请问以下红框和绿框实现的功能是一样的,这个两个写法有什么区别呢?那是说明不需要设置变量StringVar()也可以吗?还是说在特定情况下才可以?

image.png

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 21701楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/异常机制 21702楼

老师你好,你能帮我看看以下程序为什么会出现这种错误吗?

<label for="username">
    <span>用户名:</span><input type="text"  id="username"  class="username"/>
</label><br/>
    <label for="password">
    <span>密码:</span><input type="text"  id="password"  class="password"/>
</label><br/>
    <button>登陆</button>
 <script>
        var usernameInput = document.querySelector('.username');
        var passwordInput = document.querySelector('.password');
        var btn = document.querySelector('button');

        btn.onclick = function() {
            //兼容性问题,考虑兼容IE使用 ActiveXObject()  非IE使用XMLHttpRequest()
            //        xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("");
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        console.log(JSON.parse(xhr.responseText));
                    }
                }
            };

            xhr.open('post', '03post请求.php', true);

            //构建post表单数据,使用FormData类构建数据
            var datas = new FormData();
            datas.append('uname', usernameInput.value);
            datas.append('upass', passwordInput.value);
            xhr.send(datas);
        }
    </script>
<?php
     $success = array('msg'=>"ok","info"=>$POST);
    echo json_encode($success);
?>

图片.png


图片.png






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

from multiprocessing import Process
from time import sleep

class Myprocess(Process):
    def __init__(self,name):#这个name就是类里面的参数
        Process.__init__(self)
        self.name=name
    def run(self):#这个self就不需要再写个namae了 因为上面有了
        print(f"Process:{self.name}start")
        
p1=Myprocess('pcl')

p1.start()

    老师 请问报错里 为什么会出现几百行的错误 我的代码都没有那么多行


C:\Users\pcl\venv\Scripts\python.exe "C:/Users/pcl/.1aPython all exercise/线程与进程/进程实现/进程类包装.py"

Traceback (most recent call last):

  File "<string>", line 1, in <module>

  File "C:\Users\pcl\lib\multiprocessing\spawn.py", line 116, in spawn_main

    exitcode = _main(fd, parent_sentinel)

  File "C:\Users\pcl\lib\multiprocessing\spawn.py", line 125, in _main

    prepare(preparation_data)

  File "C:\Users\pcl\lib\multiprocessing\spawn.py", line 236, in prepare

    _fixup_main_from_path(data['init_main_from_path'])

  File "C:\Users\pcl\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path

    main_content = runpy.run_path(main_path,

  File "C:\Users\pcl\lib\runpy.py", line 268, in run_path

    return _run_module_code(code, init_globals, run_name,

  File "C:\Users\pcl\lib\runpy.py", line 97, in _run_module_code

    _run_code(code, mod_globals, init_globals,

  File "C:\Users\pcl\lib\runpy.py", line 87, in _run_code

    exec(code, run_globals)

  File "C:\Users\pcl\.1aPython all exercise\线程与进程\进程实现\进程类包装.py", line 13, in <module>

    p1.start()

  File "C:\Users\pcl\lib\multiprocessing\process.py", line 121, in start

    self._popen = self._Popen(self)

  File "C:\Users\pcl\lib\multiprocessing\context.py", line 224, in _Popen

    return _default_context.get_context().Process._Popen(process_obj)

  File "C:\Users\pcl\lib\multiprocessing\context.py", line 327, in _Popen

    return Popen(process_obj)

  File "C:\Users\pcl\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__

    prep_data = spawn.get_preparation_data(process_obj._name)

  File "C:\Users\pcl\lib\multiprocessing\spawn.py", line 154, in get_preparation_data

    _check_not_importing_main()

  File "C:\Users\pcl\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main

    raise RuntimeError('''

RuntimeError: 

        An attempt has been made to start a new process before the

        current process has finished its bootstrapping phase.


        This probably means that you are not using fork to start your

        child processes and you have forgotten to use the proper idiom

        in the main module:


            if __name__ == '__main__':

                freeze_support()

                ...


        The "freeze_support()" line can be omitted if the program

        is not going to be frozen to produce an executable.


Process finished with exit code 0


Python 全系列/第三阶段:Python 网络与并发编程/并发编程 21704楼
JAVA 全系列/第六阶段:项目管理与SSM框架/Mybatis 21705楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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