我在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 :(得分:1)
turtle
没有获取像素颜色的功能。它使用tkinter
(和小部件tkinter.Canvas
- turtle.getcanvas()
)来显示所有内容,但它没有获取像素颜色的功能。
Canvas将所有内容保留为对象,"Get pixel colors of tkinter canvas"的第二个答案显示如何获取位置(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()