【问题标题】:Why do the functions run as soon as my code runs? Turtle and TKinter problems [duplicate]为什么我的代码一运行这些函数就会运行? Turtle 和 TKinter 问题 [重复]
【发布时间】:2021-07-18 15:01:24
【问题描述】:

应该发生的是,我运行代码,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 

【问题讨论】:

  • 应该是command=square,不带括号。您想告诉按钮要运行哪个函数,而不是通过立即运行它来给出函数的输出。
  • 您不要在代码末尾调用window.mainloop - 请注意这次没有括号...

标签: python python-3.x tkinter python-turtle


【解决方案1】:

问题在于定义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")

【讨论】:

  • 我删除了括号,但现在没有打开任何窗口
  • 乌龟窗口打开后,您需要单击按钮。我的意思是如果你只是运行它就不会打开它
  • 感谢我的代码现在可以工作了!!!
  • 如果你想用 tkinter 打开海龟窗口,那么 - t.Screen()
【解决方案2】:

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

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")

您的代码将无法运行,因为您在文件末尾写了window.mainloop 而没有调用它,所以将其替换为window.mainloop()

您还需要致电t.exitonclick()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-24
    • 2019-10-27
    • 2020-10-20
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多