gpt4 book ai didi

python - 如何将字典值传递给回调函数?

转载 作者:行者123 更新时间:2023-12-01 04:48:18 24 4
gpt4 key购买 nike

我有一个标题字典,其值代表 3 个字母缩写。

我有一个带有标题的按钮列表,我需要 on_click 来返回缩写。

我现在返回的是标题(按钮文本),但我不知道如何传递整个字典条目,或者只是传递值。

from kivy.uix.modalview import ModalView
from kivy.uix.listview import ListView
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.app import App
import citylists
import cat_dict

from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.storage.jsonstore import JsonStore

store = JsonStore('data.json')

Builder.load_string("""
#:import ListItemButton kivy.uix.listview.ListItemButton
#:import ListAdapter kivy.adapters.listadapter.ListAdapter


<ListViewModal>:
ListView:
size_hint: .8, .8
adapter:
ListAdapter(
data=[i for i in root.categories],
args_converter=lambda row_index, rec: \
{'text': rec, 'on_press': root.callback, 'size_hint_y': None, 'height': 25},
cls=ListItemButton)

""")




class ListViewModal(ModalView):
categories = sorted(cat_dict.SECTION_DICT)

def __init__(self, **kwargs):
super(ListViewModal, self).__init__(**kwargs)

def callback(self, instance):
print "HI" + str(instance)


class MainView(GridLayout):

def __init__(self, **kwargs):
kwargs['cols'] = 1
super(MainView, self).__init__(**kwargs)

listview_modal = ListViewModal()

self.add_widget(listview_modal)

class MainScreen(Screen):
pass


mainscreen=MainScreen()
mainlayout = MainView()
mainscreen.add_widget(mainlayout)

sm = ScreenManager()
sm.add_widget(mainscreen)

class CARApp(App):

def build(self):
return sm


if __name__ == '__main__':
CARApp().run()

cat_dict.py

EECTION_DICT = {
"accounting+finance": "acc",
"admin / office": "ofc",
"arch / engineering": "egr",
'art / media / design': 'med',
'biotech / science': 'sci',
'business / mgmt': 'bus',
'customer management': 'csr',
'education': 'edu',....

最佳答案

看起来您实际上不需要向回调传递任何内容。看起来以下内容满足了您的要求:

class ListViewModal(ModalView):
section_dict = cat_dict.SECTION_DICT
categories = sorted(section_dict)

def __init__(self, **kwargs):
super(ListViewModal, self).__init__(**kwargs)

def callback(self, instance):
print "HI" + str(instance)
# Print abbreviation from dictionary lookup
print ListViewModal.section_dict[instance.text]

哪些输出:

HI<ListItemButton text=accounting+finance>acc

But one way to pass extra arguments to your callback would be to change

'on_press': root.callback
# to
'on_press': lambda inst: root.callback(inst, 'some arg')

然后更改

def callback(self, instance):
# to
def callback(self, instance, arg):

The docs除了使用 lambda 函数之外,还列出了使用 itertools.partial 作为选项。

关于python - 如何将字典值传递给回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28950836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com