[英]Turtle Graphics - Extract Color from onscreenclick
我在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()
turtle
没有获取像素颜色的功能。 它使用tkinter
(和widget tkinter.Canvas
- turtle.getcanvas()
以显示一切,但它不具备的功能让像素的颜色了。
画布将所有对象保留为对象, “获取tkinter画布的像素颜色”的第二个答案显示了如何获取位置(x,y)
中对象的颜色。 也许它将为您工作。
编辑:我做了工作的例子
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.