擅长:python、mysql、java
<p>这是因为<code>square</code>是<code>makeShape()</code>内部的局部变量,因此无法在函数外部访问它</p>
<p>您可以在<code>create_polygon()</code>中使用<code>tags</code>选项。如果要在单击正方形时移动它,<code>deleteShape()</code>根本不需要。仅仅使用<code>makeShape()</code>就足够了:</p>
<pre class="lang-py prettyprint-override"><code>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()
</code></pre>