python - 如何获取整数作为用户输入,然后在 Kivy 中用作参数?
问题描述
我是 kivy 的新手,我正在制定锻炼清单。我收集用户想要的组数,在下一个窗口中,我希望用户输入每组的重复次数。为了获得用户输入,我使用了这个
Python代码:
ActiveExerciseSet = None
class AddWorkoutWidget(Screen):
exercise_set = ObjectProperty("0")
def AddExercise(self):
ActiveExerciseSet = self.exercise_set.text
基维代码:
<AddWorkoutWidget>
exercise_set : exercise_set
Label:
text: "Number of sets "
TextInput:
id: exercise_set
input_filter: 'int'
multiline: False
Button:
text: 'Number of reps'
on_press:root.AddExercise()
现在我想使用集合的数量作为循环参数
class AddSetWidget(GridLayout,Screen):
def __init__(self, **kwargs):
super(AddSetWidget, self).__init__(**kwargs) # call grid layout parameters
self.cols = int(ActiveExerciseSet)
for I in self.col:
pass
但我不断收到TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
有没有办法把它变成一个整数?
谢谢
解决方案
我认为有一个逻辑错误。事情是这样的
ActiveExerciseSet = None # this is a global variable
class AddWorkoutWidget(Screen):
exercise_set = ObjectProperty("0")
def AddExercise(self):
ActiveExerciseSet = self.exercise_set.text #this creates a local variable within this function
所以当你触发这个函数时,全局变量仍然None
是你认为你给它赋值的地方
class AddSetWidget(GridLayout,Screen):
def __init__(self, **kwargs):
super(AddSetWidget, self).__init__(**kwargs) # call grid layout parameters
self.cols = int(ActiveExerciseSet)
#this is looking for a local variable
#and not the global variable
for I in self.col:
pass
因此,您会得到错误NoneType
- 这是正确的,因为您的全局变量被分配了一个值None
解决方案
为了使用/分配值 a global variable
,您需要使用关键字global
def AddExercise(self):
global ActiveExerciseSet#reference to global variable
ActiveExerciseSet = self.exercise_set.text
class AddSetWidget(GridLayout,Screen):
def __init__(self, **kwargs):
super(AddSetWidget, self).__init__(**kwargs) # call grid layout parameters
global ActiveExerciseSet #reference to global variable
self.cols = int(ActiveExerciseSet)
for I in self.col:
pass
推荐阅读
- c# - ASP .Net Core 路由问题?
- identityserver4 - 快速入门指南:未指定 authenticationScheme,也未找到 DefaultChallengeScheme
- sqlite - SQLite - 使用 Delphi 的 TFDQuery
- .net-core - 在 Application Insights 上显示操作名称,其中 dotnet core 3.1 应用程序的 URL 以小写形式显示
- php - 谷歌的 Laravel 身份验证不适用于警卫
- pyspark - 带有向量汇编器的 PySpark 变换方法
- outlook - 是否可以合并 Outlook 规则?
- azure - 无法使用 docker-compose 文件将 docker 映像推送到 Azure 注册表容器
- entity-framework - 如何连接这两个实体
- palantir-foundry - Foundry 中是否有可以自动填充列描述的工具?如果是这样,它叫什么?