【发布时间】:2020-12-27 00:53:33
【问题描述】:
我正在尝试编写一个代码,以水平方向上两种颜色之间的渐变形式更改一系列对象的颜色,这些对象形成一个网格。当添加另一个名为“球”的对象时,将进行此更改。我将对象放在一个数组中,并定义了一个函数,用canvas.itemconfig 迭代此更改,但是对象不会改变颜色。
import tkinter
import numpy as np
#Sizes
animation_window_width= 12800
animation_window_height= 720
animation_ball_radius = 12.5
#Function to put the ball
def place_ball(event):
canvas.unbind("<Motion>")
plate_animation()
#Function to locate the ball
def locate_ball(event):
canvas.coords(ball,
event.x-animation_ball_radius,
event.y-animation_ball_radius,
event.x+animation_ball_radius,
event.y+animation_ball_radius)
canvas.coords(tball,
event.x, event.y)
#Function to add the ball
def add_ball():
canvas.bind('<Motion>', locate_ball)
canvas.bind('<Button-1>', place_ball)
#Color gradient function
def compute_colors(start, end, limit):
(r1,g1,b1) = window.winfo_rgb(start)
(r2,g2,b2) = window.winfo_rgb(end)
r_ratio = float(r2-r1) / limit
g_ratio = float(g2-g1) / limit
b_ratio = float(b2-b1) / limit
colors = []
for i in range(limit):
nr = int(r1 + (r_ratio * i))
ng = int(g1 + (g_ratio * i))
nb = int(b1 + (b_ratio * i))
color = "#%4.4x%4.4x%4.4x" % (nr,ng,nb)
colors.append(color)
return colors
#Function to animate the mesh
def plate_animation():
color = compute_colors("red3", "blue", len(plate[0]))
for o in range(len(plate)):
for p in range(len(plate[0])):
canvas.itemconfig(plate[o][p], fill=color[p])
window = tkinter.Tk()
window.title("Mesh simulation")
window.geometry(f'{animation_window_width}x{animation_window_height}')
canvas = tkinter.Canvas(window)
canvas.configure(bg="black")
canvas.pack(fill="both", expand=True)
plate=np.zeros([12, 17])
for i in range (0, 1250, 78):
for j in range (0, 690, 62):
plate[j//62, i//78]=canvas.create_oval(i+5,j+5,i+30,j+30,fill="grey", outline="white", width=2)
ball = canvas.create_oval(0,0,0,0,fill="red", outline="white", width=2)
tball = canvas.create_text(0,0, font=("Impact", 8, "bold"), text="Ball")
tkinter.Button(window, text="Add ball", command=add_ball).pack()
window.mainloop()
知道我做错了什么吗?利用这一优势,我还想要一种方法来限制球可以占据的位置,使其只能占据网格中任何对象的位置。
【问题讨论】:
标签: python tkinter events canvas colors