如何解决如何在kivy中更改gridLayout中特定按钮的颜色
我正在尝试使用Python和Kivy制作坦波拉硬币捡拾器,而我对Kivy还是陌生的。 在这里,我创建了从1到90的gridlayout按钮。我想在选择按钮的编号时更改gridlayout中特定按钮的颜色。我面临用新的彩色按钮更新gridlayout的问题。在这里,我附上我的代码。 screenshot
#!/usr/bin/python
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Color
import random
coins = random.sample(range(1,91),90)
#print(coins)
picked_coins=[]
current_coin=0
#print(picked_coins)
class Housie(FloatLayout):
def __init__(self,**kwargs):
super(Housie,self).__init__(**kwargs)
self.title = Label(text="Housie Coin Picker",font_size = 50,size_hint=(1,.55),pos_hint={'x':0,'y':.45})
self.main_label = Label(text = "Click PICK NUMBER",.60),'y':.35})
self.picked_ones = Label(text = "picked_coins",.40),'y':.40})
self.help_button = Button(text = "PICK NUMBER",size_hint=(.3,.1),pos_hint={'x':.65,'y':.1},on_press = self.update)
self.add_widget(self.title)
self.add_widget(self.main_label)
self.add_widget(self.picked_ones)
self.add_widget(self.help_button)
self.add_widget(self.userinterface())
def userinterface(self):
self.layout = GridLayout(cols = 10,size_hint=(.50,.50))
for i in range(1,91):
self.layout.add_widget(Button(background_color=(1,1),text =str(i)))
return self.layout
def update(self,event):
for coin in coins:
if coin not in picked_coins:
current_coin=coin
picked_coins.append(coin)
self.main_label.text = str(coin)
for i in self.layout.children:
if i.text == str(coin):
#What to do Here?
break
self.picked_ones.text = "Picked coins = {}".format(" ".join(str(sorted(picked_coins))))
class app1(App):
def build(self):
return Housie()
if __name__=="__main__":
app1().run()
解决方法
您可以像这样将方法绑定到每个Button
:
def userinterface(self):
self.layout = GridLayout(cols = 10,size_hint=(.50,.50))
for i in range(1,91):
self.layout.add_widget(Button(background_color=(1,1),text=str(i),on_release=self.butt_pressed))
return self.layout
def butt_pressed(self,button):
button.background_normal = ''
button.background_color = (1,1)
butt_pressed()
方法会更改被观察的Button
的背景颜色。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。