2

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

import tkinter
root = tkinter.Tk()

but for turtle.

das-g
  • 9,718
  • 4
  • 38
  • 80
palsch
  • 5,528
  • 4
  • 21
  • 32

3 Answers3

3

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)
das-g
  • 9,718
  • 4
  • 38
  • 80
  • 2
    Thanks for correcting me! Very interesting that there are people with 5k rep using turtle / having knowledge using it. – palsch Jun 02 '18 at 14:54
  • Actually, I found your question while researching for [this answer](https://stackoverflow.com/a/50657029/674064). :-) That's also how I noticed your answer was wrong: I couldn't call `turtle.getcanvas().protocol()` – das-g Jun 02 '18 at 17:06
2

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.

fameman
  • 3,451
  • 1
  • 19
  • 31
0
turtle.getcanvas()

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

palsch
  • 5,528
  • 4
  • 21
  • 32
  • That returns the canvas, which _isn't_ the top-level widget: `assert not isinstance(turtle.getcanvas(), tkinter.Tk)`. – das-g Jun 02 '18 at 12:11