Wack-A-Mole for school - Python

可紊 提交于 2021-02-11 12:40:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!