Rotating a cube in python using tkinter
The while True
loop never exits and is preventing the code to reach top.mainloop()
, hence your canvas is never displayed.
You can replace it with a function that calls itself back using top.after
method.
from tkinter import*import mathimport timeimport numpy as npclass Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = masterclass Square(): def __init__(self, length, cx, cy): self._cx = cx self._cy = cy self._length = length self._vertices = [] self._vertices.append([-length/2,length/2]) self._vertices.append([length/2, -length/2]) self._vertices.append([length/2, length/2]) self._vertices.append([-length/2, length/2]) def rotate(self, theta): rotat_matrix = np.array([[math.cos(theta), math.sin(theta)],[-math.sin(theta), math.cos(theta)]]) #print("rotation matrix:", rotat_matrix) for i in range(len(self._vertices)): vector = np.dot(rotat_matrix,self. _vertices[i]).tolist() #print("V:", vector) self._vertices[i] = vectorsquare = Square(100, 500, 500)top = Tk()canvas = Canvas(top,bg="#EBEDEF",height=800, width=800)canvas.pack()def run(): v0 = square._vertices[0] v1 = square._vertices[1] v2 = square._vertices[2] v3 = square._vertices[3] canvas.create_line(v0[0] + 200, v0[1] + 200, v1[0]+200,v1[1]+200) canvas.create_line(v1[0] + 200, v1[1] + 200, v2[0]+200,v2[1]+200) canvas.create_line(v2[0] + 200, v2[1] + 200, v3[0]+200,v3[1]+200) canvas.create_line(v3[0] + 200, v3[1] + 200, v0[0]+200,v0[1]+200) square.rotate(math.pi/8) print("rotated") top.after(100, run)if __name__ == '__main__': run() top.mainloop()