turtle.listen() doesn't response after opening turtle input box from Tkinter button

Question:

I want to draw my turtle using arrow keys. And there’s an option to change turtle pensize.
Here’s my code:

from tkinter import *
from turtle import *

def ask():
    someinputs = numinput('Test', 'Input size:', default=1, minval=0, maxval=999)
    pensize(someinputs)

root = Tk()

Label(root, text='Settings:n').pack()
Button(root, text='Pensize', command=ask).pack()
Label(root, text=' ').pack()

def up():
    #anything here
    fd(100)
def down():
    #anything here
    bk(100)
def left():
    #anything here
    lt(90)
    fd(100)
def right():
    #anything here
    rt(90)
    fd(100)

onkey(up, 'Up')
onkey(down, 'Down')
onkey(left, 'Left')
onkey(right, 'Right')
listen()

mainloop()

But after clicking the tkinter button to set the pensize, I can’t use arrow keys to control anymore.
Can anyone help me, please? Also this doesn’t work with turtle.textinput() too!

Asked By: Hung

||

Answers:

When you use the settings window, you take focus from the turtle window. The key events will only work when the turtle window has focus. Adapting this answer it is possible to get the underlying canvas and focus it by adding Screen().getcanvas().focus_force() to the end of ask:

def ask():
    someinputs = numinput('Test', 'Input size:', default=1, minval=0, maxval=999)
    pensize(someinputs)
    Screen().getcanvas().focus_force()
Answered By: Henry

Can you not add the listen method at the end of the ask function?

def ask():
    someinputs = numinput('Test', 'Input size:', default=1, minval=0, maxval=999)
    pensize(someinputs)
    listen()
Answered By: Graham Ince