首页 > 解决方案 > 标签删除其他小部件

问题描述

Python tkinter 蛇游戏(对 python 不是很有经验)。当苹果要制作时,画布上没有显示任何内容。然后当你移动时,身体会在更多的移动后增长。每次制作苹果时,增长前的移动量都会增加 1。我认为这是因为蛇块上的标签制作和删除但我不知道如何解决这个问题。还有其他原因吗?我该如何解决?

from tkinter import *
import random

window=Tk()
window.title("snake")
window.geometry("600x600")
can=Canvas(window,height=600,width=600,background="white")
can.pack()

num=1
x3=100
y3=100
decide=3
etch_len=10
etch_wid=10
body_len=2
apple_x1=0
apple_y1=0
colour=["black"]

def move_up(self):
    global x3
    global y3
    global num
    global apple_x1
    global apple_y1
    global body_len
    if x3==apple_x1 and y3==apple_y1:
        body_len=body_len+1
        apple_make(self)
    num=num+1
    x=str(num)
    can.create_line(x3,y3,x3,(y3-etch_len),width=etch_wid,fill=colour[0],tag=x)
    y3=y3-etch_len
    remove_last(self)


def move_down(self):
    global x3
    global y3
    global num
    global apple_x1
    global apple_y1
    global body_len
    if x3==apple_x1 and y3==apple:
        body_len=body_len+1
        apple_make(self)
    num=num+1
    x=str(num)
    can.create_line(x3,y3,x3,(y3+etch_len),width=etch_wid,fill=colour[0],tag=x)
    y3=y3+etch_len
    remove_last(self)


def move_left(self):
    global x3
    global y3
    global num
    global apple_x1
    global apple_y1
    global body_len
    if x3==apple_x1 and y3==apple_y1:
        body_len=body_len+1
        apple_make(self)
    num=num+1
    x=str(num)
    can.create_line((x3-etch_wid),y3,x3,y3,width=etch_wid,fill=colour[0],tag=x)
    x3=x3-etch_len
    remove_last(self)


def move_right(self):
    global x3
    global y3
    global num
    global apple_x1
    global apple_y1
    global body_len
    if x3==apple_x1 and y3==apple_y1:
        body_len=body_len+1
        apple_make(self)
    num=num+1
    x=str(num)
    can.create_line(x3,y3,(x3+etch_wid),y3,width=etch_wid,fill=colour[0],tag=x)
    x3=x3+etch_len
    remove_last(self)


def remove_last(self):
    global num
    global body_len
    i=num-body_len
    x=str(i)
    can.delete(x)


def apple_make(self):
    global apple_x1
    global apple_y1
    apple_x1=random.randint(10,590)
    apple_y1=10
    can.create_line(apple_x1,apple_y1,apple_x1,apple_y1,width=10,fill="red")


window.bind("w",move_up)
window.bind("s",move_down)
window.bind("a",move_left)
window.bind("d",move_right)
window.bind("<Up>",apple_make)
window.mainloop()

标签: pythontkinter

解决方案


推荐阅读