如何在tkinter中删除多边形?

2024-05-14 19:43:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Tkinter中制作一个基本的游戏,包括按下开始按钮,使一个形状出现,然后当你点击该形状时,它会被删除并移动到另一个随机位置

当我尝试运行它时,我得到了NameError: name 'square' is not defined

root=Tk()
frame=Frame(root)
can = Canvas(root, width=400, height=400)
can.pack(side=TOP)

def makeShape():
    xpos = random.randint(1, 400)
    ypos = random.randint(1, 400)
    square=can.create_polygon(xpos, ypos, xpos + 40, ypos, xpos + 40, ypos + 40, 
                              xpos, ypos + 40, fill="blue")
    can.tag_bind(square,"<Button-1>",deleteShape)

def deleteShape(event):
    can.delete(square)

but1 = Button(frame, text="Start", command=makeShape)
but1.grid(row=1, column=2)

frame.pack(side=BOTTOM)
root.mainloop()

Tags: defbuttonrandomrootframecansidepack
2条回答

虽然这不是一个好的实践,但如果将行global square添加到makeShape(),它将按预期运行

这是因为如果第一次在块内指定名称,则父块或同级块将看不到该名称

有一些替代方案,考虑到可读性和实用性更好,但我的建议是解决您问题的最快方法

这是因为squaremakeShape()内部的局部变量,因此无法在函数外部访问它

您可以在create_polygon()中使用tags选项。如果要在单击正方形时移动它,deleteShape()根本不需要。仅仅使用makeShape()就足够了:

from tkinter import *
import random

root=Tk()
frame=Frame(root)
can = Canvas(root, width=400, height=400)
can.pack(side=TOP)

def makeShape():
    # delete existing square
    can.delete("square") 
    # create square at random position
    xpos = random.randint(1, 360)
    ypos = random.randint(1, 360)
    can.create_polygon(xpos, ypos, xpos+40, ypos, xpos+40, ypos+40, xpos, ypos+40,
                       fill="blue", tags="square")
    # call makeShape() when the square is clicked
    can.tag_bind("square", "<Button-1>", lambda e: makeShape())

but1 = Button(frame, text="Start", command=makeShape)
but1.grid(row=1, column=2)

frame.pack(side=BOTTOM)
root.mainloop()

相关问题 更多 >

    热门问题