2

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!

Hung
  • 155
  • 10

2 Answers2

1

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()
Henry
  • 3,472
  • 2
  • 12
  • 36
1

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()
  • Can you explain for me how that works. Also, I don't quite understand what you mean. – Hung Nov 04 '22 at 10:16
  • Before main loop(), listen() is called, this sets focus to the screen. When the button is pressed taking fouse from the screen can listen not be called again to reset focus to the screen – Graham Ince Nov 05 '22 at 14:04
  • It worked but please remove the `screen` in `screen.listen()` because I'm already import turtle with * . That's why when I added it into my code, it didn't work. But now it's ok. – Hung Nov 05 '22 at 15:57