Tkinter Canvas多边形对象问题:使用类绘制正方形失败求助
Hey there! Sorry to hear you're stuck trying to draw a square using that Tkinter polygon class method—let's work through this step by step to get it sorted.
Common Issues & Fixes
Here are the most likely culprits behind your exception, along with solutions:
Incorrect Canvas Reference in the Class
If your polygon class isn't properly receiving or storing the Tkinter Canvas instance, it'll throw errors when trying to draw. Double-check your class initialization:class PolygonDrawer: def __init__(self, canvas): self.canvas = canvas # Critical: Bind the canvas to the class instance self.points = []Make sure you're passing the actual Canvas object when creating the class instance, not a string or None value.
Malformed Square Coordinates
Squares require 4 ordered points (either clockwise or counter-clockwise) in a flat list format. If you're using nested lists (like[[x1,y1], [x2,y2]]) or have out-of-order points, you'll get weird shapes or exceptions. For a square starting at (100,100) with a 100px side length, use:square_points = [100, 100, 200, 100, 200, 200, 100, 200]Broken Draw Method Implementation
Ensure your class's draw method correctly callscanvas.create_polygonwith the right parameters. Here's a working square-specific method example:def draw_square(self, start_x, start_y, side_length): points = [ start_x, start_y, start_x + side_length, start_y, start_x + side_length, start_y + side_length, start_x, start_y + side_length ] # Add styling (fill, outline) as needed self.canvas.create_polygon(points, fill="skyblue", outline="black", width=2)Missing Tkinter Mainloop or Incorrect Call Timing
If you're trying to draw before the Canvas is fully initialized or forget to start the Tkinter main loop, nothing will render. Always wrap your app setup in aif __name__ == "__main__":block and callroot.mainloop()at the end.
Full Working Example
Here's a complete, runnable snippet you can compare against your code:
import tkinter as tk class SquareDrawer: def __init__(self, canvas): self.canvas = canvas def draw_square(self, x, y, side_length): square_points = [ x, y, x + side_length, y, x + side_length, y + side_length, x, y + side_length ] self.canvas.create_polygon(square_points, fill="lightgreen", outline="darkgreen", width=2) if __name__ == "__main__": root = tk.Tk() root.title("Square Test") canvas = tk.Canvas(root, width=400, height=400, bg="white") canvas.pack(padx=10, pady=10) drawer = SquareDrawer(canvas) drawer.draw_square(50, 50, 100) # Draw square at (50,50) with 100px side root.mainloop()
If you're still getting exceptions, take a look at the error message—things like AttributeError mean the class can't access the canvas, while TypeError points to wrong parameter types. That info will help narrow down the problem even further!
内容的提问来源于stack exchange,提问作者Swix

