微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么函数会在我的代码运行后立即运行?海龟和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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。