2016-04-13 102 views
0

我目前正在python的Turtle Graphics上制作一个程序。这里是我的代码,以防您需要它Python Turtle - Click Events

import turtle 
turtle.ht() 

width = 800 
height = 800 
turtle.screensize(width, height) 

##Definitions 
def text(text, size, color, pos1, pos2): 
    turtle.penup() 
    turtle.goto(pos1, pos2) 
    turtle.color(color) 
    turtle.begin_fill() 
    turtle.write(text, font=('Arial', size, 'normal')) 
    turtle.end_fill() 

##Screen 
turtle.bgcolor('purple') 
text('This is an example', 20, 'orange', 100, 100) 


turtle.done() 

我想要点击事件。所以,在文字'This is an example'被写入的地方,我希望能够点击它,并将其打印到控制台或更改背景。我该怎么做呢?

编辑:

我不想安装像pygame的东西,它在龟

+0

更新我的旧信息,用户点击任意位置时改变屏幕的色彩只有特定的文本显示区的位置按规定将改变屏幕的色彩 –

回答

0

由于您的要求是有文本周围区域onscreenclick,我们需要 跟踪鼠标的位置。为此,我们将函数onTextClick绑定到screenevent。 在功能范围内,如果我们有任何文字This is an example,则拨打电话turtle.onscreenclick将背景颜色更改为red。 您可以更改lambda函数并插入自己的,或只是创造外部函数和内turtle.onscreenclick调用按照this documentation

我试着改变你的代码尽可能少。

这里是工作代码:

import turtle 

turtle.ht() 

width = 800 
height = 800 
turtle.screensize(width, height) 

##Definitions 
def text(text, size, color, pos1, pos2): 
    turtle.penup() 
    turtle.goto(pos1, pos2) 
    turtle.color(color) 
    turtle.begin_fill() 
    turtle.write(text, font=('Arial', size, 'normal')) 
    turtle.end_fill() 


def onTextClick(event): 
    x, y = event.x, event.y 
    print('x={}, y={}'.format(x, y))  
    if (x >= 600 and x <= 800) and ( y >= 280 and y <= 300): 
     turtle.onscreenclick(lambda x, y: turtle.bgcolor('red')) 

##Screen 
turtle.bgcolor('purple') 
text('This is an example', 20, 'orange', 100, 100) 

canvas = turtle.getcanvas() 
canvas.bind('<Motion>', onTextClick)  

turtle.done()