我想将我的方法change_map绑定到我的按钮,并通过on_press函数将屏幕更改为“menu”。
在.kv文件中,它看起来像这样。
Button:
id: some_btn
on_press: root.change_map(); app.root.current = "menu"
我需要以pythonic方式使用它,但我收到错误“AssertionError:None不可调用”。
main.py
class MapScreen(Screen):
def __init__(self, **kwargs):
super(MapScreen, self).__init__(**kwargs)
def change_map(self, map_id):
global MAP_ID
MAP_ID = map_id
def on_enter(self, *args):
file_system = FileSystemLocal()
maps_folder = file_system .listdir('data/maps') #Gets all file names in the folder
for i in range(len(maps_folder)-1):
if "map" in maps_folder[i] and "~" not in maps_folder[i]:
map_number = maps_folder[i].replace("map", "").replace(".txt", "") # If it's a map file, get the map number
map_button = Button(text=map_number,font_name='data/fonts/Square.ttf', size_hint=(0.2, None)) #Button text is the map number
--> map_button.bind(on_press=self.change_map(map_number)) #When the button is pressed call change_map to change global var
self.ids.map_choice.add_widget(map_button) #Add the button(s) to the StackLayout in file.kv
file.kv
<MapScreen>:
canvas:
Color:
rgb: app.rgb(52, 152, 219)
Rectangle:
pos: self.pos
size: self.size
StackLayout:
id: map_choice
orientation: 'lr-tb'
size_hint: .9, .9
pos_hint: {'center_x':.5, 'center_y':.5}
答案 0 :(得分:2)
map_button.bind(on_press=self.change_map(map_number))
此调用 self.change_map,这是一个返回None的函数,因此在您尝试调用它时会出现错误。
相反,您需要传递 self.change_map以及您的默认参数。一个好方法是使用partial:
from functools import partial
map_button.bind(on_press=partial(self.change_map, map_number))