我可以在 tkinter 中使用 rgb 吗?

新手上路,请多包涵

我可以在 tkinter 中使用 rbg 而不是 hex 吗?如果是这样,我该怎么做?我计划使用此功能制作从一种颜色到另一种颜色的渐变,我计划制作一个 for 循环以在几秒钟内将其从 1 更改为 255。

 from tkinter import *

root = Tk()
root.configure(background="can i use rgb instead of hex here?")
root.mainloop()

原文由 Morton Madison Wally 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 586
1 个回答

不,tkinter 不支持 RGB,但您可以编写一个小的辅助函数来解决这个问题:

也许是这样的,其中参数 rgb 必须是表示为整数元组的有效 rgb 代码。

 import tkinter as tk

def _from_rgb(rgb):
    """translates an rgb tuple of int to a tkinter friendly color code
    """
    return "#%02x%02x%02x" % rgb

root = tk.Tk()
root.configure(bg=_from_rgb((0, 10, 255)))
root.mainloop()

如果您觉得它更具可读性,您还可以使用 fstrings 来获得完全相同的结果:

 def _from_rgb(rgb):
    """translates an rgb tuple of int to a tkinter friendly color code
    """
    r, g, b = rgb
    return f'#{r:02x}{g:02x}{b:02x}'

Note that the colorsys module from the Python standard library can help translate from HSV , HLS , and YIQ color systems

原文由 Reblochon Masque 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题