Home > Back-end >  Is it possible to use turtle objects in a tkinter screen?
Is it possible to use turtle objects in a tkinter screen?

Time:07-23

I wanted to make a sort of tennis game and I decided to use Tkinter, although I hadn't figured out how to add shapes or images to the screen. is there a way to use the turtle module to add objects using "object = "t.Turtle()" onto the tkinter screen?

CodePudding user response:

turtle already uses tkinter to display window and tkinter.Canvas() to draw in window.

I don't know if there is method to add existing turtle to new tkinter window but there is method to access already existing turtle window and use some tkinter functions - ie. add tkinter.Buttons


This example adds one button above canvas, and one button below canvas.

import tkinter
import turtle

# --- functions ---

def move():
    turtle.left(30)
    turtle.forward(50)
    
# --- main ---

canvas = turtle.getcanvas()
root = canvas.master

button1 = tkinter.Button(root, text="Before Canvas", command=move)
button1.pack(before=canvas)

button2 = tkinter.Button(root, text="After Canvas", command=move)
button2.pack() # .pack(after=canvas)

turtle.mainloop()

enter image description here


And this example puts button on canvas

import tkinter
import turtle

# --- functions ---

def move():
    turtle.left(30)
    turtle.forward(50)
    
# --- main ---

canvas = turtle.getcanvas()
root = canvas.master

root.geometry('500x500')

button = tkinter.Button(root, text="On Canvas", command=move)
canvas.create_window(0, 0, window=button)

turtle.mainloop()

enter image description here


You can also use other canvas functions to draw figures canvas.create_rectangle(), canvas.create_image(), etc. See old effbot's documentation for enter image description here

Image enter image description here

CodePudding user response:

Turtle has two models under which it operates, standalone and embedded (i.e. embedded in tkinter). Rather than poke around in turtle's underpinnings to make standalone turtle play with tkinter, we can put tkinter in charge and call up turtles as needed. Here's the first example provided by @furas redone in this manner:

import tkinter
from turtle import RawTurtle

# --- functions ---

def move():
    turtle.left(35)
    turtle.forward(50)

# --- main ---

root = tkinter.Tk()

tkinter.Button(root, text="Before Canvas", command=move).pack()

canvas = tkinter.Canvas(root)

canvas.pack()

tkinter.Button(root, text="After Canvas", command=move).pack()

turtle = RawTurtle(canvas)

root.mainloop()

Along with RawTurtle, the other embedded API objects of interest are TurtleScreen and ScrolledCanvas if you need more of standalone turtle's window features associated with the tkinter canvas upon which turtle crawls.

  • Related