2
votes

Python turtle works with tkinter. How to get the root you know from tkinter? Like this:

import tkinter
root = tkinter.Tk()

but for turtle.

3

3 Answers

3
votes

The top-level widget is available through the winfo_toplevel method of the turtle canvas:

import turtle

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

It is of a subtype of Tk:

import tkinter

assert type(root) is turtle._Root
assert isinstance(root, tkinter.Tk)
2
votes

As pointed out by @das-g

root = turtle.getcanvas().winfo_toplevel()

gives you an object representing the turtle root window.


However, if your use case is to integrate turtle graphics with a full-blown Tkinter application, the explicit approach should be preferred at all times:

from tkinter import *
import turtle

root = Tk()
turtle_canvas = turtle.Canvas(root)
turtle_canvas.pack(fill=BOTH, expand=True) # fill the entire window

protagonist = turtle.RawTurtle(turtle_canvas)
protagonist.fd(100) # etc.

This adds the extra benefit of being able to control position and size of the turtle canvas. Plus, having explicit code helps others understanding it.

0
votes
turtle.getcanvas()

returns the object you are (I am) looking for.