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

如何将指定Python函数改写为可复用的矩形类?

Refactoring to a Reusable Labeled Rectangle Class

Got it, let's turn that function into a flexible class so you can create as many custom labeled rectangles as you need—just tweak the parameters for each instance. Here's a clean, maintainable implementation:

The Class Implementation

from graphics import Rectangle, Point, Text  # Make sure you're importing your graphics library

class LabeledRectangle:
    def __init__(self, win, top_left, bottom_right, text, 
                 outline_color="darkorange2", fill_color="white",
                 text_size=35, text_face="courier", text_style="bold italic", text_color="darkorange2"):
        # Store the window reference so we can draw/undraw later
        self.win = win
        
        # Set up the rectangle with customizable colors
        self.rectangle = Rectangle(top_left, bottom_right)
        self.rectangle.setOutline(outline_color)
        self.rectangle.setFill(fill_color)
        
        # Calculate the center of the rectangle for the label (no hardcoding coordinates!)
        center_x = (top_left.x + bottom_right.x) / 2
        center_y = (top_left.y + bottom_right.y) / 2
        
        # Set up the text label with customizable styling
        self.label = Text(Point(center_x, center_y), text)
        self.label.setSize(text_size)
        self.label.setFace(text_face)
        self.label.setStyle(text_style)
        self.label.setFill(text_color)
    
    def draw(self):
        """Draw both the rectangle and label to the window"""
        self.rectangle.draw(self.win)
        self.label.draw(self.win)
    
    def undraw(self):
        """Remove both elements from the window"""
        self.rectangle.undraw()
        self.label.undraw()
    
    def update_label(self, new_text):
        """Update the label text and refresh it if already drawn"""
        self.label.setText(new_text)
        # Check if the label is already on screen to refresh it
        if hasattr(self.label, "_drawn") and self.label._drawn:
            self.label.undraw()
            self.label.draw(self.win)

How to Use It

This class lets you create multiple unique labeled rectangles with minimal code. Here's an example matching your original function, plus a second custom instance:

# Assume you've already created your window instance (win1)
# Create the original "Beats By Cuse" box
beats_box = LabeledRectangle(win1, Point(4, 15), Point(11, 13), "Beats By Cuse")
beats_box.draw()

# Create a totally different labeled rectangle
settings_box = LabeledRectangle(win1, Point(1, 5), Point(6, 3), "Settings",
                                outline_color="darkblue", fill_color="lightblue",
                                text_size=25, text_color="darkblue", text_face="arial")
settings_box.draw()

# Later, update the settings label if needed
settings_box.update_label("Updated Settings")

Why This Works Better Than the Original Function

  • Reusability: No need to copy-paste code for every new labeled rectangle—just create a new instance with your desired params.
  • Encapsulation: All related logic (rectangle, label, drawing) is bundled together in one class.
  • Flexibility: Every visual property is customizable via the __init__ parameters, so you're not locked into the original colors/styles.
  • Maintainability: If you need to change how drawing works (e.g., add an animation), you only modify the class once instead of every function call.

内容的提问来源于stack exchange,提问作者Leem2clean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:18:09