Home > Software design >  turtle.listen() doesn't response after turtle.numinput() function from Tkinter button
turtle.listen() doesn't response after turtle.numinput() function from Tkinter button

Time:07-26

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?

CodePudding user response:

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()
  • Related