问题
The command destroymole()
is unable to run without mole = tk.Button(root, ...)
,
but mole
can't run without destroymole()
How can I get them to be defined for the other one at the same time?
import tkinter as tk
import random
root = tk.Tk()
canvas = tk.Canvas(root, height=600, width=700, bg="#4f75b3")
canvas.pack()
frame = tk.Frame(root, bg="#66bd5e")
frame.place(relx=0.075,rely=0.075,relheight=0.85,relwidth=0.85,)
def destroymole():
mole.destroy()
mole = tk.Button(root, text="MOLE",relief="raised", command=destroymole(),
x=random.randint(300,700),y=random.randint(300, 700), height=20, width=30)
root.mainloop()
回答1:
You define mole
in the line mole = tk.Button(root, text="MOLE",relief="raised", command=destroymole(), x=random.randint(300,700),y=random.randint(300, 700), height=20, width=30)
, In that same line, you call the destroymole()
function and pass its return value as the command
argument, but mole
isn't defined yet so calling destroymole()
gives you an error.
What you actually meant to do was pass the function destroymole
as the command
argument so that the button would know which function to call when it is clicked. Change command=destroymole()
in that line to command=destroymole
and the error will be gone.
来源:https://stackoverflow.com/questions/65903945/wack-a-mole-for-school-python