我希望能够计算执行需要变量参数的定义函数的次数,然后每次按下ENTER键时将该计数器重置为0 < / strong>即可。我希望能够利用下面定义的函数来利用这个动作:
def draw(x):
global drawing
q.put(x)
process = False
drawingLock.acquire()
if not drawing:
process = True
drawing = True
drawingLock.release()
if process:
if not q.empty():
x()
drawingLock.acquire()
drawing = False
drawingLock.release()
此函数是queue
,它接受函数参数并逐个执行它们,此函数的参数是在 turtle graphics 窗口中绘制字母的函数。此外,此功能通过与绘制的字母对应的某个字母的按键调用。例如:
onkey(lambda: draw(draw_A), "a")
# This draws an "A" in the Turtle Graphics window when "a" is pressed on the keyboard
# If multiple "A"s pressed, it draws them one by one
如何计算用户在乌龟图形窗口中执行此draw()
函数的次数,然后每次按下ENTER键时重置它?我已经尝试为此创建一个装饰器,但是我创建的装饰器不会返回任何有龟图形的东西,并且似乎不适用于其参数可能因用户选择的参数而变化的函数。非常感谢有关此问题的任何帮助! :)
答案 0 :(得分:1)
功能允许属性:
def draw(x):
if not hasattr(draw, 'counter'):
draw.counter = 0
draw.counter += 1
# body
从用户那里抓住ENTER:
def handle_enter():
draw.counter = 0
onkey(handle_enter, 'Enter')
了解它被调用的次数:
print('`draw` has been called {} times'.format(draw.counter))