I am working on creating a game with turtle in Tkinter's Canvas Module. I have run into a problem where when I try and spawn a new turtle it spawns in a new window instead of the canvas. What have I done wrong? I would also like to resolve my issue with the quit button. I have been trying to place it in the bottom right corner. I have tried .place()
and .grid()
but without success. I have also tried other solutions on stackoverflow but they either result in an error or just disappear, probably behind the canvas.
Here is my code:
import tkinter as tk
import random
import turtle
import time
import sys
def spawn(e=None):
xrand = random.randint(0,500)
yrand = random.randint(0,500)
turtle.RawTurtle(app)
turtle.shape("square")
turtle.penup()
turtle.goto(x=xrand,y=yrand)
def systemap(e=None):
app.pack()
button.pack()
def f(e=None):
t.setheading(90)
t.forward(1)
def l(e=None):
t.setheading(180)
t.forward(1)
def r(e=None):
t.setheading(0)
t.forward(1)
def b(e=None):
t.setheading(270)
t.forward(1)
def quit(e=None):
time.sleep(1)
window.destroy()
sys.exit()
window = tk.Tk()
#window.iconbitmap('py.ico')
window.title("Turtle Graphics")
window.geometry("750x500")
window.resizable(False, False)
button = tk.Button(window, text="Exit", command = quit)
app = tk.Canvas(master=window, width=500, height=500, bg="white")
t=turtle.RawTurtle(app)
window.bind("<Up>", f)
window.bind("<Left>", l)
window.bind("<Right>", r)
window.bind("<Down>", b)
window.bind("<w>", f)
window.bind("<a>", l)
window.bind("<d>", r)
window.bind("<s>", b)
window.bind("<e>", spawn)
window.bind("<Escape>", quit)
systemap()
window.mainloop()