r/learnpython • • 3d ago

What is the point of getcanvas()? And the method get()

Hi, I'm currently on an assignment that requires me to use this function, but not only have we never seen it in class but all the research I've done haven't help me at all. My teacher also mentions the method get() in the instruction and I'm also confused by it.

Edit More details

Long story short, my assignement is to create a "forest". For that I created functions to draw the trees but I still have to create a window and a button that allows the user to choose how many trees will be drawn in it. It's at that point that I have to use the "getcanvas()" to supposedly make a window and the "get()" in a function that will be used as a command in the button.

from random import*#Used in functions
from turtle import*
from tkinter import*
from math import* #Used in functions

master= getcanvas().master #Exact line my teacher wants us to use 

screen = Screen()
screen.setup(800,500)
colormode(255)
screen.bgcolor(0, 46, 122)
speed(2000)
#What I'd like to do with it

def nbreSapin(): #Function in which I have to use 'get()' to get the number of trees
    nb= int(input("How many trees:"))
    if nb<100 and nb>0:
        getsapin(nb)
    else:
        pass
1 Upvotes

5 comments sorted by

4

u/Fun-Sandwich-2667 3d ago

Under the hood, Python's turtle module draws inside a tkinter window. Because you want to add a GUI text box and button to that same window instead of using terminal input(), you need access to the underlying Tkinter window:

  1. getcanvas().master: getcanvas() grabs the Tkinter canvas that the turtle draws on, and .master gives you the main parent window. Once you have master, you can attach Tkinter widgets (Entry and Button) directly to it.
  2. .get(): This is a method on a Tkinter Entry (input box) widget, not a standalone function. Instead of input("How many trees:") (which blocks the GUI), you read the user's input with entry.get().

Here is how to wire it into your code:

from turtle import *
import tkinter as tk

screen = Screen()
screen.setup(800, 500)
colormode(255)
screen.bgcolor(0, 46, 122)
speed(2000)

master = getcanvas().master

entry = tk.Entry(master)
entry.pack()

def nbreSapin():
    nb = int(entry.get())
    if 0 < nb < 100:
        getsapin(nb)

btn = tk.Button(master, text="Draw", command=nbreSapin)
btn.pack()

1

u/L_Y_H_ 3d ago

thank you very much for your help

1

u/Fun-Sandwich-2667 3d ago

You're welcome!

3

u/BenjaminGal 3d ago

Can you tell us more about the context? Like what is the goal of your assignment and what packages/libraries are you using?

1

u/L_Y_H_ 3d ago

Yes sorry my first post wasn't clear. I edited it with more relevant details