How to find out when the window is resized in python turtle?

Viewed 32

I have a function that draws a circle based on the screensize of the window. Currently, if I make the window smaller, the entire circle isn't visible. Is there any way to find out if the window has been resized so I can redraw the circle to fit in the window?

Here's my code to draw the circle:

def draw_circle():
    # Get circle radius
    screensize = s.screensize()
    if screensize[0] > screensize[1]:
        smaller = 1
    else:
        smaller = 0

    radius = screensize[smaller]

    # Draw circle
    t.pensize(15)
    t.pu()
    t.goto(0, -radius)
    t.pd()
    t.circle(radius)
    t.pu()

I have tried to add an if statement that checks if the screensize changes in my main loop, but that didn't work either.

P.S. I tried searching Google and StackOverflow and found no answers.

1 Answers

There's no need to poll in a loop. Once you get the underlying Tkinter canvas with turtle.getcanvas(), you can look up the non-turtle Tkinter approach and use that. For example, adapting Tkinter track window resize specifically? to turtle gives the following minimal example:

import turtle

def resize(event):
    print(event.width, event.height)

turtle.getcanvas().bind("<Configure>", resize)
turtle.exitonclick()

Note that this doesn't change the screen size, so you can draw your circle relative to the window instead:

import turtle

def draw():
    r = min(turtle.window_width(), turtle.window_height()) / 2 - 30
    turtle.clear()
    turtle.penup()
    turtle.begin_fill()
    turtle.goto(0, -r)
    turtle.pendown()
    turtle.circle(r)
    turtle.end_fill()
    turtle.update()

def resize(event):
    draw()

turtle.tracer(0)
turtle.hideturtle()
turtle.getcanvas().bind("<Configure>", resize)
draw()
turtle.exitonclick()

Drawing relative sizes for everything tends to be pretty tedious, so I recommend avoiding this if at all possible for your app.

Related