2016-04-13 12 views
0

私は現在、PythonのTurtle Graphicsでプログラムを作っています。ここに必要な場合のためのコードですPython Turtle - クリックイベント

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'が書かれているところでは、私はそれをクリックしてコンソールに何かを印刷したり、背景を変えたりしたいと思う。これはどうすればいいですか?

EDIT:

私はpygameのようなものをインストールしたくない、それは(あなたのメインループでそれに基づいて行動、その後の位置を取得するためにonscreenclickメソッドを使用して、タートル

+0

は、要件ごとのようにテキスト領域位置にのみ、特定の画面の色を変更するにはどこかをクリックすると画面の色を変更します私の古い記事を更新しました –

答えて

0

をあなたの条件は、テキスト領域の周りonscreenclickを持つことがあるので、我々は、マウスの位置を追跡する を必要としています。そのためには、関数onTextClickをscreeneventにバインドしています。 機能内で、テキストThis is an exampleの周りにanywereがある場合は、に背景の色を変更するためにturtle.onscreenclickが呼び出されます。 あなたは、ラムダ関数を変更し、独自のものを挿入し、あるいは単に外部関数を作成し、私は、できるだけ自分のコードを変更しようとしましたthis documentation

あたりとしてturtle.onscreenclick以内に呼び出すことができます。ここで

は、作業コードです:

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() 
関連する問題