问题描述
命令 destroymole()
在没有 mole = tk.Button(root, ...)
的情况下无法运行,但是mole
没有destroymole()
就不能运行我怎样才能同时为另一个定义它们?
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()
推荐答案
您在 mole = tk.Button(root, text=MOLE",relief=raised", command=destroymole(), x=random.randint(300,700),y=random.randint(300, 700), height=20, width=30)
,在同一行中,你调用destroymole()
函数并将其返回值作为command
参数传递,但mole
未定义然而,调用 destroymole()
会给你一个错误.
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.
您实际上想要做的是将function destroymole
作为command
参数传递,以便按钮会知道在单击时调用哪个函数.将该行中的 command=destroymole()
更改为 command=destroymole
,错误将消失.
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.
这篇关于学校的 Wack-A-Mole - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!