我知道在python类中,属性是在类的实例之间共享的。我正在尝试编写一个kivy应用程序,其中第一个屏幕有一个添加按钮,可以按下该按钮添加更多按钮。按钮在列表中保持跟踪,当创建新按钮时,它将被添加到列表中。
当按下按钮时,屏幕切换到定义第一个屏幕的类的另一个实例。目前,此屏幕上填充了上一屏幕中的按钮列表。有没有办法为每个类的实例提供不同的列表?
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty
from kivy.clock import Clock
from kivy.uix.screenmanager import ScreenManager, Screen
class TasksWindow(Screen):
btnHeight=.9
btnList=[]
def __init__(self):
super(TasksWindow, self).__init__()
addBtn = Button(text = "+",pos_hint= {'x': .9,'top': 1},size_hint = (.1,.1))
self.add_widget(addBtn)
addBtn.bind(on_press=self.clkAdd)
backBtn = Button(text = "Go Back",pos_hint= {'x': 0,'top': 1},size_hint = (.1,.1))
backBtn.bind(on_press=self.clkBack)
self.add_widget(backBtn)
def clkAdd(self, obj):
task = Task()
def update(self):
for x in range (0, len(self.btnList)):
temp = self.btnList.pop(x)
if (x == 0):
TasksWindow.btnHeight = .9
temp2 = Task()
self.btnList.insert(x,temp2)
del(self.btnList[len(self.btnList)-1])
self.add_widget(temp2.editBtn)
def preupdate(self,dt):
bPoint = -1
for x in range (0, len(self.btnList)):
self.remove_widget(self.btnList[x])
self.update()
def clkBack(self, obj):
sm.current = 'Screen 0'
class Task(TasksWindow):
def __init__(self):
if len(TasksWindow.btnList)==0:
TasksWindow.btnHeight = .9
self.editBtn = Button(text = "Tap to Edit",pos_hint= {'x': 0,'top': TasksWindow.btnHeight},size_hint = (.9,.1))
self.editBtn.bind(on_press=self.clkEdit)
TasksWindow.btnList.append(self)
TasksWindow.btnHeight -= .1
def clkEdit(self, obj):
screen = TasksWindow()
screen.name = ('Screen 1')
sm.add_widget(screen)
sm.current = ('Screen 1')
Clock.schedule_interval(screen.preupdate, 1.0/2.0)
sm = ScreenManager()
screen = TasksWindow()
screen.name = 'Screen 0'
sm.add_widget(screen)
sm.current = 'Screen 0'
Clock.schedule_interval(screen.preupdate, 1.0/2.0)
class TasksApp(App):
def build(self):
return sm
if __name__ == '__main__':
TasksApp().run()
此处未显示,但我使用preupdate()
和update()
的原因是我可以删除按钮。我清除所有按钮,从列表中删除已删除的按钮,然后拨打update()
。
答案 0 :(得分:0)
有没有办法为每个类的实例提供不同的列表?
当然,只需在self.the_list = []
中添加__init__
之类的内容,即可将列表设为实例属性。