我正在使用 Python 3.6.1。 我需要获取使用 Tkinter askcolor 方法选择的颜色的 RGB 值的字符串(或 int 值)。 我的代码:
from tkinter.colorchooser import askcolor
color = askcolor()
rgb_tuple = color[0] #gets tuple of RGB values
color_result_rgb = ' '.join(format(x, "1.0f") for x in rgb_tuple) #tuple into a string
现在,假设我选择了一种粉红色,其值为 (255, 0, 128)
>>> rgb_tuple
返回:
(255.99609375, 0.0, 128.5)
和
>>> color_result_rgb
返回:
'256 0 128'
如何解决此问题,使返回值正确?
最佳答案
这似乎是 tkinter1 中的错误。 askcolor
应该返回整数。修复看起来很简单:在将值转换为字符串之前将其转换为整数:
color_result_rgb = ' '.join(str(int(x)) for x in rgb_tuple)
1 查看 tkinter 代码,它确实有意返回一个 float ,即使底层的 tcl/tk 解释器返回一个 int。这似乎是 python 3.x 中 /
运算符行为变化的副作用
这是 tkinter 代码对原始值所做的事情:
r, g, b = widget.winfo_rgb(result)
return (r/256, g/256, b/256), str(result)
我已提交错误报告:askcolor is returning floats for r,g,b values instead of ints
关于python - Tkinter askcolor 返回错误的 RGB 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49866349/