简体   繁体   中英

Python turtle get tkinter root

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

import tkinter
root = tkinter.Tk()

but for turtle.

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)

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.

turtle.getcanvas()

返回您(我)正在寻找的对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM