-1

What should happen is that I run the code, the TKinter window opens and you just click a button, turtle opens and draws the shape.

However when I run my code the Tkinter window and the turtle window open but it just instantly starts drawing the shapes. Also the Tkinter window doesn't have any of the buttons either.

I'm not sure what is wrong with my code. Please can I have some help.

My code:

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 
Alex
  • 1
  • 1
    It should be `command=square` without parentheses. You want to tell the button which function to run, not give it the output of the function by running it immediately. – Thierry Lathuille Jul 18 '21 at 15:05
  • 1
    You don't call `window.mainloop` at the end of your code - note the lack of parentheses this time... – Thierry Lathuille Jul 18 '21 at 15:09

2 Answers2

1

The problem is when you define b1, b2, and b3. When you put the parentheses, the function runs. So you need to remove the parentheses like this:

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

You need to pass in the function name, not calling it so your code will be this:

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

You code will not run because you write window.mainloop at the end of the file without calling it, so replace that with window.mainloop()

You also need to call t.exitonclick()

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
SAL
  • 547
  • 2
  • 8
  • 25