How would I undo something in the python turtle module with a key press?

南笙酒味 提交于 2021-01-29 06:12:45

问题


How would I undo something in the python turtle module?

Here is my code:

turtle.listen()
turtle.onkey(undo, "ctrl + z") # You can't combine ctrl + z, so how do I do this?

回答1:


turtle is built on top of tkinter and with the latter, a control-z can be specified with "<Control-KeyPress-z>".

As stated by @martineau (+1) but with a minor correction of 'H' -> 'z'.

You can't do it with the functions that turtle provides. Python turtle doesn't pass key press symbols directly onto tkinter, it appends 'KeyPress-' onto them. So if you did the obvious:

screen.onkeypress(do_it, 'Control-z')

it will pass 'KeyPress-Control-z' instead of 'Control-KeyPress-z'. So we need to whip up a little function of our own:

from turtle import Screen, Turtle

def oncontrolkeypress(self, fun, key):
    def eventfun(event):
        fun()

    self.getcanvas().bind("<Control-KeyPress-%s>" % key, eventfun)

def do_it():
    turtle.circle(100)

def undo_it():
    turtle.undo()

turtle = Turtle()

screen = Screen()
screen.onkeypress(do_it, 'c')
oncontrolkeypress(screen, undo_it, 'z')
screen.listen()
screen.mainloop()

Type 'c' to draw a circle. Type a control 'z' to undraw it.

To keep it simple, I've left off the usual features of a turtle key binding function where you can pass None for the key to bind all control keys and pass None for the function to unbind the key.



来源:https://stackoverflow.com/questions/63431581/how-would-i-undo-something-in-the-python-turtle-module-with-a-key-press

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!