为什么我的乌龟 onclick 函数在 while 循环中不起作用?

问题描述 投票:0回答:1

你好,我正在尝试使用 python 中的海龟制作枪动画。我已经完成了第一部分,但是我用来设置动画的 while 循环不允许 onclick 函数工作。

这是我的代码:

import time
penup()
speed(0)
canvas = getscreen()
hideturtle()
bullet_x = 0

gun_color = input("Enter the color: ")

def draw_gun():
    #gun is a rectangle and a square
    
    
    #handle
    goto(-150, 0)
    pendown()
    begin_fill()
    color(gun_color)
    for i in range(4):
        forward(20)
        right(90)
    end_fill()
        
                
    
    #top of toy gun
    penup()
    goto(-60, 50)
    pendown()
    begin_fill()
    color(gun_color)
    for i in range(4):
        right(90)
        if (i + 1)%2 != 0:
            forward(50)
        else:
            forward(100)
        penup()
    end_fill()
    
def water_bullet():
    begin_fill()
    goto(-30, bullet_x)
    circle(30)
    color("deepskyblue")
    end_fill()
    
bullet_shot = False
    
def bullet_spawn(x,y):
    bullet_shot = True

canvas.onclick(bullet_spawn)

while(True):
    time.sleep(0.5)
    clear()
    bgcolor("#F5F5DC")
    draw_gun()
    if (bullet_shot == True):
        bullet_x = bullet_x + 1
        water_bullet()

感谢您的帮助

我尝试用水弹制作一把枪,但找不到解决问题的文档。

python turtle-graphics python-turtle
1个回答
0
投票

您似乎缺少以下代码:

def bullet_spawn(x,y):
    bullet_shot = True

onscreenclick(bullet_spawn) # replace with 'canvas.onclick(bullet_spawn)'

海龟文档链接

© www.soinside.com 2019 - 2024. All rights reserved.