I need to create a grid of triangles like in this picture: https://www.tilelook.com/system/tile_picture/resource/4973584/d3d_default_RE04MC017.png .
As i want the triangles to be clickable I'm using canvas function create_polygon
for drawing and bind
function for listening to the click event. The problem is that i need to draw many triangles and this would require to calculate by hand the vertices of each triangle.
Is there a faster method like drawing some parallel and intersecting lines and tell tkinter that the vertices are the intersections of the lines or something that doesn't involve calculating the vertices of each triangle?
While you can't get the intersections from within tkinter
you could instead make triangles with a couple for
loops and then plot these on the canvas. An example would look like:
import tkinter as tk
import random
def make_triangles(row_height=60, tri_width=60, max_height=1800, max_width=1800):
triangle_list = []
half_width = int(tri_width/2)
for i in range(0, max_height, row_height):
for j in range(0, max_width, half_width):
if j % tri_width == 0:
triangle = (i, j-half_width, i+row_height, j, i, j+half_width)
else:
triangle = (i, j, i+row_height, j+half_width, i+row_height, j-half_width)
triangle_list.append(triangle)
return triangle_list
win = tk.Tk()
canv = tk.Canvas(win)
triangles = make_triangles()
for tri in triangles:
canv.create_polygon(tri, fill=random.choice(["blue", "red", "green", "brown", "yellow", "black"]))
canv.pack()
win.mainloop()
Where we just generate many triangles and then plot them successively onto the canvas (we don't have to find each vertex by hand, just a formula that would describe them all). While this doesn't solve your exact problem in that the triangles don't intersect (you would have to shift every other row by half a triangle), and the triangles are left/right instead of up/down, it does answer your question " Is there a shortcut for creating many polygons with tkinter "! The answer is to just make a list of your polygons and then plot them all. A sample output (yours will be different because it is random) of my code looks like:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.