为什么总项目函数没有打印出语句



为什么当我运行代码时,"def total_item(("函数中的"print(len(val_holder(("不起作用。它不会打印出语句。当所有三个按钮以有序或无序的方式单击时,它将在"val_holder"中存储一个项目,最后它应该打印出"val_holder"中的项目总数


import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label 
val_holder=[]
class LandingScreen(FloatLayout):
def __init__(self, **kwargs):
super(LandingScreen, self).__init__(**kwargs)
# put whatever pos_hint value you want.          
self.btn1=Button(text='button1 ', size_hint=(0.5, 0.5), 
on_press=self.click_b1))
self.btn2=Button(text='button1 ', size_hint=(0.5, 0.5), 
on_press=self.click_b2))
self.btn3=Button(text='button1 ', size_hint=(0.5, 0.5), 
on_press=self.click_b3))


self.add_widget(self.btn1)
self.add_widget(self.btn2)
self.add_widget(self.btn3)
def click_b1(self, instance):
val_holder.append('a') 
def click_b2(self, instance):
val_holder.append('b')
def click_b3(self, instance):
val_holder.append('c') 
#The function below is not printing out the statement.
def total_item():
print(len(val_holder))  
total_item()
class SplashApp(App):
def build(self):
return LandingScreen()
if __name__ == '__main__':
SplashApp().run()
  • 您无法看到print(len(val_holder))语句的结果,因为当您初始化LandingScreen对象时,val_holder仍然是空的。然后,当对象完全初始化时,单击三个按钮之一,它将向val_holder添加项,但因为您没有再次调用total_item()函数,因此您看不到任何内容。请尝试以下操作:
import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label 
val_holder=[]
class LandingScreen(FloatLayout):
def __init__(self, **kwargs):
super(LandingScreen, self).__init__(**kwargs)
# put whatever pos_hint value you want.          
self.btn1=Button(text='button1 ', size_hint=(0.5, 0.5), 
on_press=self.click_b1))
self.btn2=Button(text='button1 ', size_hint=(0.5, 0.5), 
on_press=self.click_b2))
self.btn3=Button(text='button1 ', size_hint=(0.5, 0.5), 
on_press=self.click_b3))


self.add_widget(self.btn1)
self.add_widget(self.btn2)
self.add_widget(self.btn3)
def click_b1(self, instance):
val_holder.append('a') 
total_item() # new line
def click_b2(self, instance):
val_holder.append('b')
total_item() # new line
def click_b3(self, instance):
val_holder.append('c') 
total_item() # new line
#The function below is not printing out the statement.
def total_item():
print(len(val_holder))  

class SplashApp(App):
def build(self):
return LandingScreen()
if __name__ == '__main__':
SplashApp().run()

希望对您有所帮助!!

最新更新