單擊按鈕時,如何更改隨機拋出的圖像的不透明度? (使用kivy)。如何在按下kivy上的按鈕時改變不透明度
from random import randint
from random import random
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.graphics import Color, Line, Rectangle
from kivy.uix.filechooser import FileChooserListView, FileChooserIconView
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.uix.floatlayout import FloatLayout
class MyBackground(Widget):
def __init__(self, **kwargs):
x = randint(1,10)
print (x)
y = 'water.png'
if x==1:
y = 'a.png'
if x==2:
y = 'b.png'
if x==3:
y = 'c.png'
if x==4:
y = 'd.png'
if x==5:
y = 'e.png'
if x==6:
y = 'f.png'
if x==7:
y = 'g.png'
if x==8:
y = 'h.png'
if x==9:
y = 'i.png'
if x==10:
y = 'j.png'
super(MyBackground, self).__init__(**kwargs)
with self.canvas:
Color(1, 1, 1, 0.5)
self.bg = Rectangle(source=y, pos=self.pos, size=self.size)
self.bind(pos=self.update_bg)
self.bind(size=self.update_bg)
Color(1, 0, 1, 0.5)
def update_bg(self, *args):
self.bg.pos = self.pos
self.bg.size = self.size
class MyPaintWidget(Widget):
def on_touch_down(self, touch):
with self.canvas:
Color(1, 1, 1)
d = 30.
touch.ud['line'] = Line(points=(touch.x, touch.y))
def on_touch_move(self, touch):
touch.ud['line'].points += [touch.x, touch.y]
class MyRandomApp(App):
def build(self):
layout = BoxLayout(spacing=10, orientation='vertical')
b = BoxLayout(spacing=0)
btn1 = Button(text='opacity 40%', size_hint=(.2, .2))
btn3 = Button(text='opacity 20%', size_hint=(.2, .2))
btn4 = Button(text='opacity 10%', size_hint=(.2, .2))
btn5 = Button(text='opacity 0%', size_hint=(.2, .2))
b.add_widget(btn1)
b.add_widget(btn3)
b.add_widget(btn4)
b.add_widget(btn5)
layout.add_widget(b)
background = MyBackground(size_hint=(1, 10))
layout.add_widget(background)
painter = MyPaintWidget()
layout.add_widget(painter)
return layout
if __name__ == '__main__':
MyRandomApp().run()
我試着在類MyRandomApp()中有一個定義,但它表示它沒有屬性到畫布。
這是非常有幫助的。但是有一個問題,爲什麼你必須把「自我」放在一切之前?謝謝! –
使用'self'關鍵字可以創建一個類實例屬性。然後您可以在其他類功能中引用該屬性。它比這更深,是Python中的一個重要概念。 [link](http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self-in-python)也許是一個開始的地方 – therealpickle