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.

0

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for correcting me! Very interesting that there are people with 5k rep using turtle / having knowledge using it.
Actually, I found your question while researching for this answer. :-) That's also how I noticed your answer was wrong: I couldn't call turtle.getcanvas().protocol()
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.

Comments

0
turtle.getcanvas()

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

1 Comment

That returns the canvas, which isn't the top-level widget: assert not isinstance(turtle.getcanvas(), tkinter.Tk).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.