命令destroymole()不能在没有mole = tk.Button(root, ...)的情况下运行,但是mole不能在没有destroymole()的情况下运行--如何同时为另一个命令定义它们?
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()发布于 2021-01-26 15:23:14
在行mole中定义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()会给出一个错误。
实际上,您要做的是传递函数destroymole作为command参数,以便按钮在单击该函数时知道该调用哪个函数。将该行中的command=destroymole()更改为command=destroymole,错误将消失。
https://stackoverflow.com/questions/65903945
复制相似问题