为什么函数会在我的代码运行后立即运行?海龟和TKinter问题

问题描述

应该发生的事情是我运行代码,TKinter 窗口打开,您只需单击一个按钮,turtle 打开并绘制形状。

但是,当我运行我的代码时,Tkinter 窗口和海龟窗口会打开,但它会立即开始绘制形状。此外,Tkinter 窗口也没有任何按钮。

我不确定我的代码有什么问题。请我帮忙。

我的代码

import tkinter as tk
import turtle as t

window = tk.Tk()
window.geometry("500x500")

def square():
    t.forward(200)
    t.right(90)
    t.forward(200)
    t.right(90)
    t.forward(200)
    t.right(90)
    t.forward(200)
    t.exitonclick

def triangle():
    t.forward(200)
    t.right(135)
    t.forward(200)
    t.right(115)
    t.forward(200)
    t.exitonclick

def rectangle():
    t.forward(200)
    t.right(90)
    t.forward(100)
    t.right(90)
    t.forward(200)
    t.right(90)
    t.forward(100)
    t.exitonclick

b1 = tk.Button(window,command=square(),text="Square",bg="Red")
b2 = tk.Button(window,command=triangle(),text="Triangle",bg="Cyan")
b3 = tk.Button(window,command=rectangle(),text="Rectangle",bg="Gold")

b1.place(x=0,y=0)
b2.place(x=0,y=30)
b3.place(x=0,y=60)

window.mainloop 

解决方法

问题在于您定义 b1b2b3 时。当你加上括号时,函数就会运行。所以你需要像这样删除括号:

b1 = tk.Button(window,command=square,text="Square",bg="Red")
b2 = tk.Button(window,command=triangle,text="Triangle",bg="Cyan")
b3 = tk.Button(window,command=rectangle,text="Rectangle",bg="Gold")
,

你需要传入函数名,而不是调用它,所以你的代码是这样的:

b1 = tk.Button(window,bg="Gold")

你的代码不会运行,因为你在文件末尾写了 window.mainloop 而没有调用它,所以用 window.mainloop() 替换它

您还需要调用 t.exitonclick()