You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter Canvas多边形对象问题:使用类绘制正方形失败求助

Troubleshooting Square Drawing Issues with Tkinter Polygon Class

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 calls canvas.create_polygon with 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 a if __name__ == "__main__": block and call root.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:58:44