Python 3.x 如何在不再次写入整行的情况下修改参数?
嗨,我正在尝试一些方法覆盖,但我不知道怎么做。我有一个叫做RectCreator的类Python 3.x 如何在不再次写入整行的情况下修改参数?,python-3.x,parameters,pygame,Python 3.x,Parameters,Pygame,嗨,我正在尝试一些方法覆盖,但我不知道怎么做。我有一个叫做RectCreator的类 class RectCreator: def __init__(self, location_x, location_y, width, height, ): self.location_x = location_x self.location_y = location_y self.width = width self.height =
class RectCreator:
def __init__(self, location_x, location_y, width, height, ):
self.location_x = location_x
self.location_y = location_y
self.width = width
self.height = height
def creating_rect(self, display, color):
creating_rect = pygame.Rect(self.location_x, self.location_y, self.width, self.height)
drawing_rect = pygame.draw.rect(display, color, creating_rect, border_radius=20)
return creating_rect, drawing_rect
这个类在一个文件中。我在main.py中导入了该文件,我使用的类如下:
button_1 = RectCreator(350, 350, 100, 100)
btn_1 = button_1.creating_rect(display_surface, blue)
btn_1 = button_1.creating_rect(display_surface, green) ---------------> I DONT WANT TO WRITE THAT
这就是我想做的。我不知道如何更改btn_1的颜色,而不再次这样写所有行:
button_1 = RectCreator(350, 350, 100, 100)
btn_1 = button_1.creating_rect(display_surface, blue)
btn_1 = button_1.creating_rect(display_surface, green) ---------------> I DONT WANT TO WRITE THAT
我试图向类中添加一个color方法,并将该方法放入使用color的方法中
def color(self, color):
return color
def creating_rect(self, display):
creating_rect = pygame.Rect(self.location_x, self.location_y, self.width, self.height)
drawing_rect = pygame.draw.rect(display, self.color(), creating_rect, border_radius=20)
return creating_rect, drawing_rect
这是我的解决方案,但self.color()要求我提供一个参数。我想做的就是:
btn_1 = button_1.creating_rect(display_surface, blue)
**output : a blue box that display on my app**
btn_1.change_color(green)
**output : now that blue box turned to green box**
一旦你在屏幕上画了一些东西(比如一个矩形),它就会留在屏幕上,直到你在同一位置画出新的东西,它才会消失。例如,如果将位置
5,12
处的屏幕像素设置为绿色,则无法在不与屏幕表面再次交互的情况下神奇地更改该位置处的颜色
因此,如果你画一个蓝色的矩形,现在想要一个绿色的矩形,你必须再次调用pygame.draw.rect
。仅仅改变一个随机变量是不够的
您可以做的是向类中添加一个颜色属性,并使用该属性更改无论如何都必须绘制每个帧的矩形的颜色(可能存在例外):
然后,创建一个实例,并在主循环中继续调用draw
。然后,只需设置color
属性即可更改颜色
import random
...
btn_1 = RectCreator(350, 350, 100, 100)
...
while True:
for e in pygame.event.get():
if e.type == pygame.KEYDOWN:
btn_1.color = random.choice(('blue', 'green', 'red', 'yellow'))
btn_1.draw(display_surface)
...
pygame.display.flip()
你为什么不写呢。添加一个
color
属性怎么样?实际上没有具体的原因。但它确实帮助我接受不同的解决方案。您可以使用默认参数(def creating_rect(self,display,color=green)
)或属性(self.color
)ok@rabbi76我会试试。谢谢你,谢谢你。我没有想到要这样使用“self.color”属性。