2017-11-19 2 views
0

私は大きなプログラムのためにPythonでTurtle Graphicsを使用しています。ユーザーがクリックした点をturtle.onscreenclickで返すことができますタートルグラフィックス - オンスクリーンからの色の抽出

ただし、ユーザーがクリックするポイントのRGBカラーを抽出したいと思います。これは亀のグラフィックでもできますし、これをどのように達成できますか?ありがとうございました!

import turtle 

# Global variables specifying the point clicked 

xclick = 0 
yclick = 0 

# Draw a rectangle that is red 

height = float(50) 
length = height *(1.9) 
length = round(length,2) 
turtle.begin_fill() 
turtle.color("red") 
turtle.down() 
turtle.forward(length) 
turtle.right(90) 
turtle.forward(height) 
turtle.right(90) 
turtle.forward(length) 
turtle.right(90) 
turtle.forward(height) 
turtle.right(90) 
turtle.end_fill() 

# Gets the click 

def getcoordinates(): 
    turtle.onscreenclick(turtle.goto) 
    turtle.onscreenclick(modifyglobalvariables) 

# Modifies the global variables  

def modifyglobalvariables(rawx,rawy): 
    global xclick 
    global yclick 
    xclick = int(rawx//1) 
    yclick = int(rawy//1) 
    print(xclick) 
    print(yclick) 

getcoordinates() 
turtle.done() 

答えて

0

turtleには、ピクセルカラーを取得する機能がありません。 tkinter(そしてウィジェットtkinter.Canvas - turtle.getcanvas())を使ってすべてを表示しますが、ピクセルの色を取得する機能はありません。

キャンバスはすべてオブジェクトとして保持され、"Get pixel colors of tkinter canvas"の2番目の答えは、位置が(x,y)のオブジェクトの色を取得する方法を示しています。多分それはあなたのために働くでしょう。


EDIT:私が働いて作った例

canvasは異なる座標を使用しています - それはy = -y

import turtle 

# --- functions --- (lower_case_names) 

def get_pixel_color(x, y): 

    # canvas use different coordinates 
    y = -y 

    canvas = turtle.getcanvas() 
    ids = canvas.find_overlapping(x, y, x, y) 

    if ids: # if list is not empty 
     index = ids[-1] 
     color = canvas.itemcget(index, "fill") 
     if color != '': 
      return color.lower() 

    return "white" # default color 

def modify_global_variables(rawx,rawy): 
    global xclick 
    global yclick 

    xclick = int(rawx) 
    yclick = int(rawy) 

    print(get_pixel_color(xclick, yclick)) 


def draw_rect(x1, y1, width, height, color): 
    y1 = -y1 
    canvas = turtle.getcanvas() 
    canvas.create_rectangle((x1, y1, x1+width, y1+height), fill=color, width=0) 

# --- main --- 

# Global variables specifying the point clicked 

xclick = 0 
yclick = 0 

# Draw a rectangle that is red 

height = 50.0 # now it is float 
length = height * 1.9 
length = round(length, 2) 

turtle.down() 
turtle.color("RED") 

turtle.begin_fill() 

for _ in range(2): 
    turtle.forward(length) 
    turtle.right(90) 
    turtle.forward(height) 
    turtle.right(90) 

turtle.end_fill() 

# Use tkinter.Canvas to draw rectangle 

draw_rect(100, 100, length, height, 'green') 

# Gets the click & Modifies the global variables  

turtle.onscreenclick(modify_global_variables) 

turtle.done() 
を変更する必要が
関連する問題