我很好奇是否有一种方法可以直接反转中的颜色。我见过PIL模块允许使用图像(作为文件),但我想应用在画布内部仍然可见的变化,其中包含形状。 e.g:
import tkinter
canvas=tkinter.Canvas()
canvas.pack()
canvas.create_rectangle(20,20,60,60,fill='blue', outline='red')
你能帮助我,如何改变颜色?
答案 0 :(得分:1)
有趣的问题。我一次只能更改一个画布项目的颜色,但我可以编写一个功能来完成全部或部分画布。例如:
import tkinter
root = tkinter.Tk()
root.geometry('300x200')
canvas = tkinter.Canvas()
canvas.pack(expand='yes', fill='both')
canvas.create_rectangle(20,20,60,60,fill='blue', outline='red')
canvas.create_line(100,100,160,160,fill='blue')
def invert_color(color): # Invert color
if type(color) == str: rgb = canvas.winfo_rgb(color)
else: rgb = color
rgb = (65535-rgb[0], 65535-rgb[1], 65535-rgb[2])
tk_rgb = "#%04x%04x%04x" % (rgb)
return tk_rgb
def invert_canvas(event):
# Check or select canvas items:
items = canvas.find_withtag('all')
# Loop through canvas items
for item in items:
fill = canvas.itemcget(item, "fill") # Get fill color
if fill != '': fill = invert_color(fill)
if canvas.type(item) in ['rectangle','arc']:
outline = canvas.itemcget(item, "outline") # Get outline color
outline = invert_color(outline)
canvas.itemconfig(item, fill=fill, outline=outline) # Set colors
else:
canvas.itemconfig(item, fill=fill) # Set colors
root.bind('<space>', invert_canvas)