为什么这个猴子补丁对 python 乌龟不起作用?

Why doesn't this monkey patch work for python turtle?

所以我正在尝试对 turtle 中的 onkey 函数进行猴子修补,以便它在按下按钮时调用函数,而不是不带任何参数地调用它。我正在使用字符串“tester”来查看它是否有效,但看起来原始函数从未发生过变化。有人可以解释我做错了什么吗?

from threading import Thread
from time import sleep
from turtle import *

def NEWonkeypress(self, fun, key=None):
    if fun is None:
        if key in self._keys:
            self._keys.remove(key)
    elif key is not None and key not in self._keys:
        self._keys.append(key)
    self._onkeypress(fun, key)

def _NEWonkeypress(self, fun, key=None):
    if fun is None:
        if key is None:
            self.cv.unbind("<KeyPress>", None)
        else:
            self.cv.unbind("<KeyPress-%s>" % key, None)
    else:
        def eventfun(event):
            fun("tester")
        if key is None:
            self.cv.bind("<KeyPress>", eventfun)
        else:
            self.cv.bind("<KeyPress-%s>" % key, eventfun)

Turtle.onkeypress = NEWonkeypress
Turtle._onkeypress = _NEWonkeypress

board = Turtle()
screen = board.getscreen()
screen.tracer(0, 0)
temp = Turtle()

def textinput(testing):
    print(testing)

def getroomname(option): 
    global temp
    global board
    #Box
    temp.fillcolor("White")
    temp.width(10)
    temp.goto(-150, -60)
    temp.down()
    temp.begin_fill()
    for x in range(2):
        temp.forward(300)
        temp.left(90)
        temp.forward(120)
        temp.left(90)
    temp.end_fill()
    temp.up()
    temp.goto(0, 100)
    screen.update()
    #Box
    temp.goto(0, -60)
    screen.onkeypress(textinput)
    listen()
    

getroomname(0)
mainloop()

(这只是主要代码的一小段,所以不用担心它在space中绘制的随机方块)

它实际上比你做的要简单,我们只需要稍微改变一下。当您 运行 下面的代码时,您键入的任何键都应该通过 turtle 的事件系统传递并打印到控制台:

from functools import partial
from turtle import Screen, Turtle

def getroomname():
    temp.penup()
    temp.goto(-150, -60)
    temp.pendown()
    temp.begin_fill()

    for _ in range(2):
        temp.forward(300)
        temp.left(90)
        temp.forward(120)
        temp.left(90)

    temp.end_fill()

def _onkeypress(self, fun, key=None):
    if fun is None:
        if key is None:
            self.cv.unbind("<KeyPress>", None)
        else:
            self.cv.unbind("<KeyPress-%s>" % key, None)
    else:
        def eventfun(event):
            fun(event.char)

        if key is None:
            self.cv.bind("<KeyPress>", eventfun)
        else:
            self.cv.bind("<KeyPress-%s>" % key, eventfun)

def keyinput(key):
    print(key)

screen = Screen()
screen._onkeypress = partial(_onkeypress, screen)  # monkey patch (protected access)

temp = Turtle()
temp.speed('fastest')
temp.fillcolor("white")
temp.width(10)

getroomname()

screen.onkeypress(keyinput)
screen.listen()
screen.mainloop()

我简化了你不相关的代码。但是,您没有正确使用 global,因此我建议您在 运行 遇到麻烦之前先查看相关教程。此外,您执行了 from turtle import * 但随后执行了 def textinput(...),其中 textinput 也是 Python 3 乌龟的方法 - 因此请避免执行 from turtle import * 以避免更多麻烦。